Selim
Selim

Reputation: 197

Supposed to get the child but somehow gets the parent ID

Good day. I have a code. To my understanding, the clicked2 should get the id "Third" since it's looking for the children. But somehow, it always get the id "First". How do i get the "Third"?

<!DOCTYPE html>
<html>
<body>

    <div class="menu" id="First">
       <button id="Second">eee</button>
       <button id="Third">yyy</button>
    </div>
    <div class="holder"></div>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">

          $(document).on('click', '.menu', function(e) {
               var clicked = e.target.id || this.id;
               var clicked2 = e.target.children.id || this.id;
               var y = clicked2.replace(/\D/g, '');
               var x = clicked.replace(/\D/g, '');
               var w = 0;

               $('.holder') .append('<BR>'+clicked+'<BR>'+clicked2);

               });

   </script>

</body>
</html>

Upvotes: 2

Views: 58

Answers (2)

Shrinivas Pai
Shrinivas Pai

Reputation: 7701

Add this var clicked2 = $(this).children("button").next().attr("id") It will return id of the second button.

Try this

$(document).on('click', '.menu', function(e) {
var clicked = e.target.id || this.id;
var clicked2 = $(this).children("button").next().attr("id") || this.id;


var y = clicked2.replace(/\D/g, '');
var x = clicked.replace(/\D/g, '');
var w = 0;

$('.holder') .append('<BR>'+clicked+'<BR>'+clicked2);

   });

Demo Here

Upvotes: 1

BobbyTables
BobbyTables

Reputation: 4685

children() returns all the childrens, so you need to adress the right one:

var clicked2 = $(this).children().next().attr("id");

Upvotes: 0

Related Questions