Add class according to text by JS / Jquery

Asked

Viewed 31 times

0

I am styling radio-button and need to add class according to the text of the button. Actually it is very simple and works with the code below, I need that instead of inserting the data-title="" be inserted as class=""

$('td').each(function() {
  $(this).attr('data-title', $(this).text());
});

Ou sem jQuery:

for (let el of document.getElementsByTagName('td')) {
  el.dataset.title = el.innerText.trim();
}

I can’t remember the right way.

  • 2

    Face wouldn’t just be changing data-title for class in that part $(this).attr('data-title', ... ?

  • That’s right, it went blank! Thank you

1 answer

1


With jQuery you can manage the classes with:

$('td').each(function() {
    const el = $(this);
    el.addClass( el.text() );
});

And without jQuery basically the same thing, captures the element and manages the classes

const el = document.querySelectorAll('td');
for (var i = 0, n = el.length; i < n; i++) {
    const element = el[i];
    element.classList.add( el.textContent );
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.