jquery: addClass 1,2,3 etc. auto to a list
is it possible, to add auto numeric classes to a list by using jquery?
html:
<ul id="list">
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
<li>Element 4</li>
<li>Element 5</li>
</ul>
i want to get something like this:
<ul id="list">
<li class="1">Element 1</li>
<li class="2">Element 2</li>
<li class="3">Element 3</li>
<li class="4">Element 4</li>
<li class="5">Element 5</li>
</ul>
hope there is a solution available :-)
Edit
ok, mhhm but my list has not always a number at the end. so what's about a classname combination, like "item + number" ? is something like this possible?
<ul id="list">
<li class="item1">Element x</li>
<li class="item2">Element开发者_运维知识库 c</li>
<li class="item3">Element a</li>
<li class="item4">Element d</li>
<li class="item5">Element f</li>
</ul>
$("#list li").each(function(i) {
this.addClass("item"+(i+1));
});
Here it is in action
http://jsbin.com/ocake
Update per comments, as in example link this works :
$(document).ready(function() {
$("#list li").each(function(i) {
$(this).addClass("item" + (i+1));
});
});
But I think initial code should work by adding :
this = $(this);
But not sure.
$("#list").children().each(function(i) {
$(this).addClass("prefix_" + (i+1));
});
CSS 2 has some special rules relating to numeric class names. See the grammar, specifically "class" within G.1, "nmstart" in G.2, and the final bullet point in G.3.
Using classes .c1 through .c5:
$('#list li').each(function(){
$(this).addClass( 'c' + $(this).text().substr(-1) );
});
Note that this assumes the very last character of the <li>
is a number. You may have to tweak (possibly using regex) for your exact use case.
For jQuery 1.4.x:
$("#list > li").addClass(function(i){return "item" + (i + 1);});
$('ul#list li').each(function(){
$(this).addClass( $(this).text().split(' ')[1] );
});
ok, mhhm but my list has not always a number at the end. so what's about a classname combination, like "item + number" ? is something like this possible?
<ul id="list">
<li class="item1">Element x</li>
<li class="item2">Element c</li>
<li class="item3">Element a</li>
<li class="item4">Element d</li>
<li class="item5">Element f</li>
</ul>
精彩评论