jquery nested selector
How can I grab the nested element "4"?
I tried:
var nights = $("div.nights h5 div.num").val();
and:
var nights = $(开发者_JS百科"div.nights > h5 > div.num").val();
example:
<div class="nights">
<h5 class="biguns">
<div class="num">4</div>
Nights
</h5>
</div>
Use .text()
here instead, like this:
$("div.nights h5 div.num").text() // descendant selector
//or this works too:
$("div.nights > h5 > div.num").text() // child selector
//or just
$("div.num").text(); // chaining tag and class selector
You can test it here, as you can see above, your selector is flexible, use what works on your overall markup. .val()
is for input type elements, e.g. <input>
, <select>
, <textarea>
, <button>
...to get the text inside of any other element, use .text()
instead.
$("div.nights div").text()
but not
$("div.nights > div").text()
because descendant selector: A descendant of an element could be a child, grandchild, great-grandchild, and so on, of that element. child selector: Selects all direct child elements specified by "child" of elements specified by "parent".
reference child selector descendant selector
精彩评论