I need to grab the text value of a child div.
<div id='first'> <div id='first_child'>A</div> <div id='second_child'>B</div> <div id='third_child'>C</div> </div>
I am trying to grab the value B. I am currently trying this but it is not working,
var text_val = $('#first').next('#second_child').val();
The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
jQuery children() function. jQuery children() method is used to get the direct children of the selected HTML element. You can use children() method to traverse through the child elements of the selected parent element.
children() is an inbuilt method in jQuery which is used to find all the children element related to that selected element. This children() method in jQuery traverse down to a single level of the selected element and return all elements. Syntax: $(selector).children()
Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.
You want to use children()
and text()
instead of val()
. Although, since what you are selecting has an id (and ids must be unique), you could also simply select based on the id without involving the container element at all.
The val()
method only works on input elements, textareas, and selects -- basically all form elements that contain data. To get the textual contents of a container, you need to use text()
(or html()
, if you want the mark up as well).
var text_val = $('#second_child').text(); //preferred
or
var text_val = $('#first').children('#second_child').text(); // yours, corrected
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With