Home >Web Front-end >JS Tutorial >Why Avoid `document.write()` and What are the Better Alternatives?
Avoiding document.write
In HTML tutorials, document.write() is commonly introduced, but its usage is often discouraged. This is because document.write has severe limitations:
Alternatives to document.write
Here are some alternatives to document.write that are more appropriate in most situations:
createElement() and appendChild()
This approach involves creating a new HTML element using createElement() and appending it to the DOM using appendChild(). It allows you to insert content without overwriting the existing page.
innerHTML
innerHTML is a property that can be used to set the content within an existing element. This method is convenient for updating specific portions of the page without affecting the rest of the content.
insertAdjacentHTML()
This method allows you to insert HTML code relative to a specified element. It provides various options for inserting before, after, or within the element.
Example
To illustrate the usage of createElement() and appendChild(), consider the following code:
const container = document.getElementById('container'); const newElement = document.createElement('p'); newElement.textContent = 'Hello, world!'; container.appendChild(newElement);
This code creates a
element with the text "Hello, world!" and adds it to the container element without overwriting the existing content.
The above is the detailed content of Why Avoid `document.write()` and What are the Better Alternatives?. For more information, please follow other related articles on the PHP Chinese website!