21

How can I grab the nested element "4"?

I tried:

var nights = $("div.nights h5 div.num").val();

and:

var nights = $("div.nights > h5 > div.num").val();

example:

<div class="nights">
        <h5 class="biguns">
            <div class="num">4</div>
            Nights
        </h5>
</div>

2 Answers 2

28

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ah, yes... i knew it was something so simple my brain was going to explode. thanks.
@nick Yaaa, great answer, can you please edit the answer and add what type of selector, in a comment
4
$("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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.