Reputation: 67
How can i get the content text of an element in order to use as class.
<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
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
Reputation: 99
$( "li" ).each(function() {
var text = $(this).find('a').text();
$( this ).addClass(text);
});
Like so
Upvotes: 1
Reputation: 4206
Here you go. You basically set the class
attribute to the text
value.
Upvotes: 1
Reputation: 144689
You can simply use the .addClass()
callback function and .text()
method:
$('ul li').addClass(function() {
return $(this).text();
});
Upvotes: 6