Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery selector returns undefined

This html code was generated of my php code, but I copied this out of the HTML code of the browser.

The console.log prints out undefined. I don't know why. It's probably a really dumb mistake, like always. Thank you for your help.

$('.show').click(function() {
  var id = $(this).attr('id');
  var div = $("div#" + id);
  console.log(div.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Heading <a href='#' class='show' id='2962'>+</a></h3>
<div class='.slidetoggle' id='2962' style='display: none;'>
  <p>Test!</p>
</div>
like image 707
phil Avatar asked Sep 18 '26 22:09

phil


1 Answers

It's because the .show element is an a, not a div. The selector is wrong:

var div = $("a#" + id);

Update:

You are right, but I want to show the div, not the a

In this case you need to use DOM traversal to find the relevant element. Your current code doesn't work as you have duplicate id attributes. This is invalid as they must be unique. Try this:

$('.show').click(function() {
  $(this).closest('h3').next('.slidetoggle').slideToggle();
});
.slidetoggle { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Heading <a href="#" class="show">+</a></h3>
<div class="slidetoggle">
  <p>Test!</p>
</div>

<h3>Another Heading <a href="#" class="show">+</a></h3>
<div class="slidetoggle">
  <p>Another Test!</p>
</div>
like image 158
Rory McCrossan Avatar answered Sep 21 '26 10:09

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!