0

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.

The sidebar to help visulize

xeo
  • 807
  • 2
  • 7
  • 25
cosmichero2025
  • 1,029
  • 4
  • 14
  • 37
  • [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Mohamed-Yousef Jan 15 '18 at 02:39
  • The information that you have supplies shows the content that you are looking for is within a variable and not part of the web page itself. That is why it isn't working. –  Jan 15 '18 at 02:39

1 Answers1

2

You need to delegate the event since the divs 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>
Adam Azad
  • 11,171
  • 5
  • 29
  • 70
  • It worked! I also didn't know about needing to do things differently when content is generated dynamically like that. I'll give you a check when I can! – cosmichero2025 Jan 15 '18 at 02:49