Home > Article > Web Front-end > How to Append HTML to the DOM Without Using innerHTML?
Appending HTML to the DOM Without Using InnerHTML
When appending HTML strings to the DOM, you may encounter scenarios where using div.innerHTML = str; is unacceptable. In such cases, you can leverage the insertAdjacentHTML method, which is supported by all modern browsers.
To append a HTML string to a div with the id "test," you can use the following code:
var str = '<p>Just some <span>text</span> here</p>'; var div = document.getElementById('test'); div.insertAdjacentHTML('beforeend', str);
The insertAdjacentHTML method allows you to insert the HTML string before the end of the specified element, ensuring its insertion inside the element. The "beforeend" position parameter specifies that the HTML should be added after the last child of the element.
By utilizing the insertAdjacentHTML method, you have a versatile and efficient way to append HTML to the DOM without resorting to the innerHTML property, which can have performance implications and security vulnerabilities in certain contexts.
The above is the detailed content of How to Append HTML to the DOM Without Using innerHTML?. For more information, please follow other related articles on the PHP Chinese website!