Search code examples
jqueryaddclass

JQUERY How to add class with text inside element


It's possible with jquery add class with the content of p?

<p>red</p>
<p>blue</p>
<p>green</p>

like

<p class="red">red</p>
<p class="blue">blue</p>
<p class="green">green</p>

Solution

  • You can do it like below:

    $('p').each(function () {
        this.className = this.textContent; //get the text within the element and set it as class name
    });
    

    Demo Fiddle

    In Fiddle, check console.log for the output.

    Note: .innerHTML can be used but it is better to use .textContent when dealing with only text.