Reputation: 2329
I want to show / console the children content of $(this)
. See below the codes:
<div id="thumb-2" class="thumb">
<span id="info-2" class="blurb">More Info</span>
</div>
<div id="thumb-3" class="thumb">
<span id="info-3" class="blurb">Atlast</span>
</div>
<script>
$(document).ready(function(){
$(this).click(function(){
console.log($(this).children('.blurb').text());
});
});
</script>
But it shows nothing in the console.
The output will be:
- When I click div with id 'thumb-2', it will console as 'More Info'
- When I click div id with 'thumb-3', it will console as 'Atlast'
Upvotes: 1
Views: 1039
Reputation: 720
You can try the code below
$(document).on('click', '.thumb', function(){
var thumb = $(this);
console.log(thumb.children('.blurb').text())
//console.log(thumb.find('.blurb').text()) //another way
})
Upvotes: 0
Reputation: 149
$(document).ready(function(){
$(this).click(function(e){
let target = $(e.target);
console.log(target.children('.blurb').text());
});
});
Modify your code as shown above and you will get desired output. In your case $(this) has context bound to document object.The children() method returns all direct children of the selected element.The only direct children of document is html. html doesn't have blurb class set. So you are getting undefined.There is another method called find() to counter the problem.Find transverses to all the nested children of a selection.But You have bound click event to whole document hence it will output text content of both .blurb elements. As shown in my code snippet above you can capture the target of click event. If it has direct children named blurb fetch the text node.
Upvotes: 0
Reputation: 34267
You are not passing the parent control into jQuery.
Use the associated class thumb
to lookup that elements children.
$(function() {
$('.thumb').click(function() {
console.log($(this).children('.blurb').text());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="thumb-2" class="thumb">
<span id="info-2" class="blurb">More Info</span>
</div>
<div id="thumb-3" class="thumb">
<span id="info-3" class="blurb">Atlast</span>
</div>
Upvotes: 3