Reputation: 13213
Not sure how to explain this, but I would like to target a selector only within this
.
So lets say I have
<ul>
<li class=a></li>
<li class=b></li>
<li class=c></li>
</ul>
And I execute this:
$("li").each(function(i,v){
$(".a",$(this)).append("1");
$(".b",$(this)).append("2");
$(".c",$(this)).append("3");
});
Unfortunately this doesn't work as expected, but I'm sure there is a way that it does.
I've tried using if hasClass("a")
,etc. but I would like to avoid that route if possible. Any suggestions?
I also know I can do $("li:eq("+i+").a")
as a selector, but I am trying to use this
here.
Unfortunately this doesn't work either: $(this).find(".a")
Upvotes: 0
Views: 30
Reputation: 318182
You want to do something more like this
$("li").each(function(i,v){
if ( $(this).hasClass('a') ) $(this).text("1");
if ( $(this).hasClass('b') ) $(this).text("2");
if ( $(this).hasClass('c') ) $(this).text("3");
});
It's the LI that has the class, so you have to check it, right now you're using the context selector wich searches for an element with that class inside the LI.
Also note that when you're not appending elements but really just setting the elements text, use text()
As a final sidenote, your example could also be done like this
$("li").text(function(i) { return i+1 })
But I'm guessing it's just an example and that you didn't just want a number ?
Upvotes: 1