最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get a specific child divs value from parent using jquery - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Oct 8, 2013 at 16:19 Brian Phillips 4,4252 gold badges28 silver badges40 bronze badges asked Oct 8, 2013 at 15:53 OptimusOptimus 2,2109 gold badges38 silver badges72 bronze badges 3
  • Try var id = $(this).children(".testId")[0].innerHTML; – Arun P Johny Commented Oct 8, 2013 at 15:54
  • Why use innerHTML when you can use .html() or .text()? – Sterling Archer Commented Oct 8, 2013 at 15:56
  • One probable reason is if you click a child element of the parent then it will not work.... so try $(this).closest('.main').children(".testId").html() – Arun P Johny Commented Oct 8, 2013 at 15:57
Add a ment  | 

5 Answers 5

Reset to default 6

Try using find():

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

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

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

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

I think this one should works

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

here is a working exmaple

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="http://code.jquery./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>
发布评论

评论列表(0)

  1. 暂无评论