Re-initialize HTML selector after DOM was changed via AJAX

Submitted by Peter Majmesku on Tue, 03/14/2017 - 10:07

Once I was searching for a method to trigger my HTML markup, after I have changed it via an AJAX request. I could not find any non-irritating solution. So I have implemented a "common" cheap solution for this, which was documented at many places in the web (like Stackoverflow threads with many votes on a post). In the old approach, I have loaded JavaScript, which was placed within the fetched HTML markup. This resulted in an ugly structure. Because my HTML and JavaScript was mixed and not entirely separated in files.

Here is an example code with the better solution, which works by separated files:

var initFilterInput = function(el) {
el.find('form input').click(function(event) {
el.load('/reduced-filters', function() {
console.log"Load was performed." );



In this example I initialize an event listener on a HTML element, which is located by the "filter-group" CSS class. This happens after the entire page load. After the click event is triggered, some HTML markup will be replaced in the current HTML DOM tree. Then this function will call itself by


and the event triggering still works on the new HTML markup.

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.