开发者

jquery nested selector

开发者 https://www.devze.com 2023-01-19 01:21 出处:网络
How can I grab the nested element \"4\"? I tried: var nights = $(\"div.nights h5 div.num\").val(); and:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号