4

This is my HTML code:

<ul class="nav nav-tabs">
    <li class="active"><a href="#menu1" data-toggle="tab">menu1</a></li>
    <li><a href="#menu2" data-toggle="tab">menu2</a></li>
</ul>

This is my javascript code which changing the innerHTML:

document.body.innerHTML = document.body.innerHTML.replace( text1, text2 );

and this my jquery code for handling events:

$('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) { 
    alert('test');
}); 

when the java code to change innerHTML is running, the event of tab is not working anymore

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109

2 Answers2

4

The problems is when you are replacing the inner html all the elements in which you have binded the event handlers are destroyed and new elements are created which does not have any event handlers added to them.

This approach have further issues in that any plugins that was initialized on those elements are also destroyed so those also won't work.

So the correct solution will be is to iterate over each target element and then replace the necessary content.

As for the event handlers alone is considered, your can use event delegation, but still the bootstrap plugin might not work because in the new elements the plugin is not initialized.

document.body.innerHTML = document.body.innerHTML.replace(text1, text2);
$(document.body).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
    alert('test');
});
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Use Jquery to handle the replacement instead:

$(document).find('body').html(text);

Gene Lim
  • 1,068
  • 2
  • 14
  • 36