Reputation: 119
I have this element:
<div id="divOne">
<button class="close-menu">close</button>
<ul>
<li>hello</li>
</ul>
</div>
I want to copy inner html of #divOne and paste it to other div when page is loading.
I do with this code but my button does not work anymore.
document.getElementById('divTwo').innerHTML = document.getElementById("divOne").innerHTML;
Thank you
Upvotes: 1
Views: 2720
Reputation: 119
For those who still see this post:
If you want the buttons (onClick event,...) work after adding new HTML to an element, use the code below:
element.insertAdjacentHTML(position, text);
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
Upvotes: 0
Reputation: 122898
You need to delegate the click handler, something like
// handle clicks on all document buttons
$(document).on('click', 'button', buttonClick);
// copy #divOne html to #divTwo
$('#divTwo').html($('#divOne').html());
// click handler demo
function buttonClick(e) {
var result = $('#result');
var id = $(this.parentNode).attr('id');
result.html('clicked button within: #' + id);
// comment @cssGeek demo
$('div').css('color', '#000');
$('#'+id).css('color', 'red');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divOne">
<button class="close-menu">close</button>
<ul>
<li>hello</li>
</ul>
</div>
<div id="divTwo"></div>
<div id="result"></div>
Upvotes: 3
Reputation: 1546
try this
document.getElementById('divTwo').innerHTML = document.getElementById("divOne").innerHTML;
<div id="divOne">
<button class="close-menu">close</button>
<ul>
<li>hello</li>
</ul>
</div>
<div id="divTwo"></div>
Upvotes: 0
Reputation: 74738
my button does not work anymore.
Well in this case you have to delegate the event to the closest static parent or to the document
:
I guess you are using jquery:
$(document).on('click', '.close-menu', function(e){
console.log('clicked.');
});
I want to copy inner html of #divOne and paste it to other div when page is loading.
What you have posted is doing it other way round instead you have to do this:
document.getElementById('divTow').innerHTML = document.getElementById("divOne").innerHTML;
Upvotes: 1