简体   繁体   中英

Does using innerHTML prevent clientside javascript from applying on new html?

I am using .innerhtml to take information from a form, and re-display a list(of dynamic data that displays in the form of a credit card. See following link for example. https://codepen.io/quinlo/pen/YONMEa ) to the DOM. However, when I display that information back to the DOM, my client side Javascript does not seem to apply towards the new elements by re-reading their id's and class's.

Snippit of relevant code

var renderElement = document.querySelector(".cardbox");
const html = '<div class="card-container preload" id="target" >'+
       '<div class="creditcardrender">'+
       '                            <div class="front">'+
       '                                <div id="ccsingle"></div>'+ ... etc

renderElement.innerHTML += html;

Is this a property of HTML/Javascript that is unavoidable or is there a work-around this issue?

thanks.

If I understood the question correctly,

Using renderElement.innerHTML += html; is equivalent to renderElement.innerHTML = renderElement.innerHTML + html; , which means its value is a new string resulted from the concatenation of the two strings. So, the existing HTML element will be refactored as if you're assigning it from scratch.

To add the HTML code you're hoping to be present, you can use insertAdjacentHTML() function to add the HTML code to the element without reforming the existing code.

renderElement.insertAdjacentHTML('beforeend', html)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM