I am trying to pull out some HTML (a hrefs) from a long string of data returned in an AJAX call from the server and then add these to the DOM, tried following several examples on the prior answers but cannot seem to get the DOM element to be clickable though it appears to be added as a link. So, have stepped back and trying to add one new element when clicking on another and can’t get this working either – have tried in jsfiddle, basic example of code is as follows below – when clicking on the getsearchresults, the a href is displayed within the searchresults div but when clicked does not fire the .clicakable_search handler.
HTML
Get search results
results
JS code
$(document).ready(function() {
$("#getsearchresults_id").click(function(event) {
var aa = $('<a href="#" class="clickable_search">parsed substring from the return data</a>');
$('#searchresults').append(aa);
});
$('.clickable_search').click(function(e) {
console.log(".clickable_search");
e.preventDefault();
alert('anchor without a href was clicked');
});
});
it’s because it didn’t exist in the dom at the time of binding. Delegation binds the event handler to a parent element that will in turn listen for the event as it bubbles up. Make sure the parent element is a static element
use delegation – preferred way if using jQuery 1.7+
jQuery 1.7 and lower
or bind after element is added to dom – this will add multiple if clicked multiple times