Skip to content Skip to sidebar Skip to footer

How To Access First Child Div Of The Parent Div

On a click event for a div, I'm trying to assign a variable the text value of the first child of that divs parent div. For example, the html is something like this:
).html();

Solution 2:

You can use a combination of child > and :first selectors. Like this:

var divValue = $(".parentDiv>div:first").text();

This will select the first child div element and retrieve it's text value.

Here is a working example

Of course, if you have a class for it anyway you can just use $(".firstChild").text(); but I assume that was just to help explain the question.

Solution 3:

$(function(){
  $('.parentDiv div').click(function(){
    var $parent = $(this).closest('.parentDiv');
    //Do whatever you want with $parent
  });
});

Use jQuery tree traversal to find the parent (the .closest bit)

Solution 4:

.parentDiv:first-child or .parentDiv:first or .parentDiv:nth-child(1) or even .firstChild:first-of-type

Solution 5:

You won't want to use a second selector, as that makes for slow performance. Instead, search within your current element with .find()

var text = 'new text';
$('.parentDiv').on('click', function() {
  $(this).find('div:first').html(text);
});

Post a Comment for "How To Access First Child Div Of The Parent Div"