April 12, 2012

replace innerhtml along with events

Question by user1032531

I would like to replace the innerhtml of thisOne with that of either clone1 or clone2.

I have figured out how to replace the entire thisOne element with that of the clone, but would rather not do it that way as I store data in the li element.

I also have figured out how to put a separate div tag around the clones innerhtml, clone(true) that redundant tag element, and append the redundant tag and its innerhtml into thisOne, but these seems like a waste of a tag.

I also find that html() doesn’t bring over the events, and would rather not re-declare them each time I swap the html.

Any suggestions? Thank you

<ul>
<li id="thisOne" data-attr="whatever"></li>
</ul>

<ul style="display: none">
<li id="clone1">
<a href="#" class="doSomething1">Click</a>
<button class="doSomething3">Click</button>
</li>
<li id="clone2">
<a href="#" class="doSomething2">Click</a>
<button class="doSomething4">Click</button>
</li>
</ul>

....

$("clone1 a").click(function(){alert("hi");});

The following new code added doesn’t appear to work.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Dialogs</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" language="javascript"></script>
<script type="text/javascript">
$(document).ready(function(){    
    $("#cloneIt").click(function(){$('#newLocation').html($('#clone').html());});
    $("#clone a").on("click", function(){alert("click");});
    $("#clone select").on("change", function(){alert("change");});

});
</script>

</head>
<body>
<input type="button" value="Clone it" id="cloneIt" />

<div id="newLocation"></div>

<div id="clone" style="display: none">
<a href="#">Click Me</a>
<select><option>Hello</option><option>Goodby</option></select>
</div>

</body>
</html>

Answer by ocanal

you can iterate children, than append cloned each one to thisOne

   $("#clone1, #clone2").each(function() {
        $(this).children().each(function() {
                $("#thisOne").append($(this).clone(true));
        });
    });

Answer by Starx

You have to delegate the event so that it waits future occurrences of the selector as well.

It very easy like this

$("#clone1 a").on("click", function(){alert("hi");});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!