Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery rebind after using html()

Tags:

html

jquery

I am using JQuery .Html() to swap around the divs on my page using this code:

    $('#item1').html($('#item8').html());
    $('#item8').html('<p>sdsdsd</p>');

I've found that this works great, however the JQuery methods stop working. So div #item1 will have a toggle for example, it will work fine until I use .html().

Is there any solution to rebind the JQuery to fix this?

Thanks!

like image 333
Funky Avatar asked Mar 29 '26 02:03

Funky


1 Answers

Instead of getting the HTML of the elements and then having the browser reparse it into another element, you could just move nodes from one container to another:

var $item8 = $('#item8');
$('#item1').empty().append($item8.contents());
$item8.html('<p>sdsdsd</p>');

This will keep any current bindings on the already created elements, so there's no need to use live() or rebind those events.

live(), or rather, delegate() is still a decent alternative solution, however.

like image 196
Andy E Avatar answered Apr 01 '26 08:04

Andy E