I have a HTML structure:
<div class="mydiv">xx
<span>test1</span>
<span>test2</span>
<div class="inerdiv">
<span>inner span</span>
</div>
</div>
<span>test3</span>
Now I want to apply styling to the span which contains "inner span" .
$(function() {
$(".mydiv").click(function() {
$(".mydiv").next().find("span").css("border", "1px solid yellow");//not working
});
});
what should be the proper code?
I have a HTML structure:
<div class="mydiv">xx
<span>test1</span>
<span>test2</span>
<div class="inerdiv">
<span>inner span</span>
</div>
</div>
<span>test3</span>
Now I want to apply styling to the span which contains "inner span" .
$(function() {
$(".mydiv").click(function() {
$(".mydiv").next().find("span").css("border", "1px solid yellow");//not working
});
});
what should be the proper code?
Share Improve this question asked Nov 19, 2009 at 11:40 WonderingWondering 5,09622 gold badges73 silver badges90 bronze badges 1- Dup? stackoverflow./questions/1606629/… – moxn Commented Nov 19, 2009 at 11:48
3 Answers
Reset to default 5Replace:
$(".mydiv").next().find("span").css("border", "1px solid yellow");
With:
$(".mydiv .innerdiv span").css("border", "1px solid yellow");
I don't think next()
does what you think it does.
next()
returns the immediate next sibling of all previous matched elements.
Given the markup:
<div class="hello">foo1</div><span>bar1</span>
<div class="goodbye">foo2</div><span>bar2</span>
<div class="hello">foo3</div><span>bar3</span>
The following will return the span elements containing bar1
and bar3
:
$("div.hello").next()
Therefore, there's no way to get the <div class="innerdiv">
from the outer div
using next()
, since they are not siblings.
$(function() {
$(".mydiv").click(function() {
$(".innerdiv span", this).css("border", "1px solid yellow");
});
});
$ (.mydiv .inerdiv span:contains('inner span')).css("border", "1px solid yellow")