Home  >  Article  >  Web Front-end  >  How to Append HTML to the DOM Without Using innerHTML?

How to Append HTML to the DOM Without Using innerHTML?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 23:46:31704browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn