Reputation: 67
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>
Upvotes: 3
Views: 6490
Reputation: 337560
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>
Upvotes: 6
Reputation: 159
I don't have the reputation to comment yet so I will have to give it as an answer, but the element you want is an nchor but your jQuery selector is targeting a element.
Upvotes: 1