0

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:

<div class="parentDiv">
    <div class="firstChild">
        1234
    </div>

    <div class="secondChild">
        Hello
    </div>

    <div class="thridChild">
        Bye
    </div>

</div>

So I want it to assign a variable the text value of the firstChild div whenever the click on anything inside the parent div. How would you go about doing this?

spark4102
  • 11
  • 4
  • Possible duplicate of http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class or http://stackoverflow.com/questions/5852452/how-to-select-first-child-with-jquery – Refilon Nov 20 '14 at 15:20

5 Answers5

1

You can use:

var text = $('.parentDiv:nth-child(1)').html();
twain
  • 1,305
  • 11
  • 16
0

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.

musefan
  • 47,875
  • 21
  • 135
  • 185
0
$(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)

ggdx
  • 3,024
  • 4
  • 32
  • 48
0

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

darcher
  • 3,052
  • 3
  • 24
  • 29
0

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);
});
Will Stern
  • 17,181
  • 5
  • 36
  • 22