📅  最后修改于: 2023-12-03 14:42:07.195000             🧑  作者: Mango
insertAdjacentHTML
is a Javascript method which allows you to add new HTML content to a specific position in an element. This method comes in handy when you want to dynamically change the contents of an HTML element without having to recreate the entire contents of the element.
The syntax for using the insertAdjacentHTML
method is as follows:
element.insertAdjacentHTML(position, text);
Here, element
represents the HTML element to which you want to add the new HTML content. position
represents the position at which you want to add the new content. There are four possible values for position
. They are:
"beforebegin"
: inserts the new HTML content directly before the specified element"afterbegin"
: inserts the new HTML content at the beginning of the specified element"beforeend"
: inserts the new HTML content at the end of the specified element"afterend"
: inserts the new HTML content directly after the specified elementThe text
parameter represents the HTML content that you want to add to the specified element.
Here are some examples of how you can use the insertAdjacentHTML
method in your Javascript code.
const element = document.getElementById("myElement");
element.insertAdjacentHTML("beforebegin", "<h2>Hello World!</h2>");
This code will add an <h2>
heading with the text Hello World!
just before the element with the ID myElement
.
const element = document.getElementById("myElement");
element.insertAdjacentHTML("afterend", "<h2>Hello World!</h2>");
This code will add an <h2>
heading with the text Hello World!
just after the element with the ID myElement
.
insertAdjacentHTML
is a powerful method that allows you to easily add new HTML content to your webpage without having to recreate the entire contents of an element. It's easy to use and can save you a lot of time and effort when it comes to dynamically updating your webpage.