Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get value within child div

Tags:

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(); 
like image 756
medium Avatar asked Feb 22 '10 17:02

medium


People also ask

How to access child element in jQuery?

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.

How to get child element from parent in jQuery?

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.

What is children() in jQuery?

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()

How do you get the children of the $( this selector?

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.


1 Answers

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  
like image 94
tvanfosson Avatar answered Sep 19 '22 06:09

tvanfosson