how to access inner span tag in jquery
I ha开发者_StackOverflow社区ve 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?
Replace:
$(".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")
精彩评论