Reputation: 1029
I have a sidebar with a list of generated divs each of which have a p tag inside of them that contain the name of a font. I'm trying to get the text in the p tag. For some reason my code isn't working for the dynamically added elements, but it works on other elements I've tried it with.
HTML (Template)
var content = '<div class="trending-font d-flex w-100 justify-content-between list-group-item"><p>' + item.family + '</p><small>' + item.lastModified + '</small></div>';
JS
$('.trending-font').click(function () {
var $sideBarFont = $(this).find('p').text();
console.log($sideBarFont);
});
When I run it there are no errors and nothing on the page is broken it just doesn't return the text inside of the clicked div.
Upvotes: 0
Views: 46
Reputation: 11297
You need to delegate the event since the div
s are appended on the fly to the DOM.
$(document).on('click', '.trending-font', function () {
var $sideBarFont = $(this).find('p').text();
console.log($sideBarFont);
});
$(document).on('click', '.trending-font', function () {
var $sideBarFont = $(this).find('p').text();
console.log($sideBarFont);
});
var content = '<div class="trending-font d-flex w-100 justify-content-between list-group-item" ><p> family 1 </p><small> Jan 3, 2018</small></div>';
$('#c').append( Array(5).join(content) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="c"></div>
Upvotes: 2