Obeck
Obeck

Reputation: 67

Jquery add content text of an li element to a class

How can i get the content text of an element in order to use as class.

jsfiddle

<ul>
   <li><a href="#">blue</a></li>
   <li><a href="#">red</a></li>
   <li><a href="#">orange</a></li>
   <li><a href="#">green</a></li>
</ul>

after:

<ul>
   <li class="blue"><a href="#">blue</a></li>
   <li class="red"><a href="#">red</a></li>
   <li class="orange"><a href="#">orange</a></li>
   <li class="green"><a href="#">green</a></li>
</ul>

Upvotes: 0

Views: 115

Answers (4)

Awlad Liton
Awlad Liton

Reputation: 9351

Try this : Live demo: http://jsfiddle.net/H9RDv/13/

$( document ).ready(function() {
  $( "li" ).each(function() {
    cl = $(this).text();
    $( this ).addClass(cl);
});
});

Output:

<ul>
    <li class="item1"><a href="#">item1</a></li>
    <li class="item2"><a href="#">item2</a></li>
    <li class="item3"><a href="#">item3</a></li>
    <li class="item4"><a href="#">item4</a></li>
</ul>

Upvotes: 1

Tijme
Tijme

Reputation: 99

$( "li" ).each(function() {
    var text = $(this).find('a').text();
    $( this ).addClass(text);
});

Like so

Upvotes: 1

mjkaufer
mjkaufer

Reputation: 4206

Here you go. You basically set the class attribute to the text value.

http://jsfiddle.net/H9RDv/2/

Upvotes: 1

Ram
Ram

Reputation: 144689

You can simply use the .addClass() callback function and .text() method:

$('ul li').addClass(function() {
   return $(this).text();
});

http://jsfiddle.net/3hV28/

Upvotes: 6

Related Questions