Optimus
Optimus

Reputation: 2210

How to get a specific child divs value from parent using jquery

I know this question is so familiar in stackoverflow, but still I can't find my solution. I want to get my child div's value when I click the parent div, but my current code gives me "undefined". My html is given below:

<div class="main">
  <div class="testId">
    1
  </div>
  <div class="testName">
    test
  </div>
  <div class="testDob">
    10/10/10
  </div>

</div> 

and my script is given below

var id = $(this).child(".testId").innerHTML;

any thoughts?

Upvotes: 3

Views: 10768

Answers (5)

Stuart
Stuart

Reputation: 1151

here is a working exmaple

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
    <div class="main">
               <div class="testId">
               1
               </div>
               <div class="testName">
               test
               </div>
               <div class="testDob">
               10/10/10
               </div>

            </div> 

    <script>
        $(".main").click(function () {
            var id = $(this).children(".testId").html();
            alert(id)
        })
    </script>
</body>
</html>

Upvotes: 1

prakashapkota
prakashapkota

Reputation: 321

"find" finds the elements just inside the div.main

var id = $(this).find(".testId").html();
console.log(id);

Upvotes: 3

Liauchuk Ivan
Liauchuk Ivan

Reputation: 2003

I think this one should works

$('.main').click(function(){
    var value = $(this).child(".testId").text();
})    

Upvotes: 1

Use .children() no selector .child()

var id = $(this).children(".testId")[0].innerHTML;

or

var id = $(this).children(".testId").text();

or

var id = $(this).children(".testId").eq(0).text();

Upvotes: 2

Brian Phillips
Brian Phillips

Reputation: 4425

Try using find():

var id = $(this).find(".testId").text();

Upvotes: 6

Related Questions