Element node

Introduction

The Element node object corresponds to the HTML element of the web page. Every HTML element will be transformed into an Element node object (hereinafter referred to as element node) in the DOM tree.

The nodeType attributes of element nodes are all 1.

var p = document.querySelector("p");
p.nodeName; // "P"
p.nodeType; // 1

The Element object inherits the Node interface, so the attributes and methods of Node exist in the Element object.

In addition, the element nodes corresponding to different HTML elements are different. The browser uses different constructors to generate different element nodes. For example, the constructor of the <a> element is HTMLAnchorElement(), <button> is HTMLButtonElement(). Therefore, element nodes are not an object, but many kinds of objects. In addition to inheriting the attributes and methods of the Element object, these objects also have their own unique attributes and methods.

Instance attributes

(1)Element.id

The Element.id property returns the id property of the specified element, which can be read and written.

// HTML code is <p id="foo">
var p = document.querySelector("p");
p.id; // "foo"

Note that the value of the id attribute is case sensitive, that is, the browser can correctly recognize the id attributes of the two elements <p id="foo"> and <p id="FOO">. But it's better not to name it like that.

(2)Element.tagName

The Element.tagName property returns the uppercase tag name of the specified element, which is equal to the value of the nodeName property.

// HTML code is
// <span id="myspan">Hello</span>
var span = document.getElementById("myspan");
span.id; // "myspan"
span.tagName; // "SPAN"

** (3) Element.dir **

The Element.dir property is used to read and write the text direction of the current element, which may be left to right ("ltr") or right to left ("rtl").

(4)Element.accessKey

The Element.accessKey property is used to read and write the shortcut key assigned to the current element.

// HTML code is as follows
// <button accesskey="h" id="btn">点击</button>
var btn = document.getElementById("btn");
btn.accessKey; // "h"

In the above code, the shortcut key of the btn element is h, and you can press Alt + h to shift the focus to it.

(5)Element.draggable

The Element.draggable property returns a boolean value indicating whether the current element is draggable. This attribute can be read and written.

** (6) Element.long **

The Element.lang property returns the language setting of the current element. This attribute can be read and written.

// HTML code is as follows
// <html lang="en">
document.documentElement.lang; // "en"

(7)Element.tabIndex

The Element.tabIndex property returns an integer that represents the order of the current element during Tab key traversal. This attribute can be read and written.

If the value of the tabIndex attribute is negative (usually -1), the Tab key will not traverse to the element. If it is a positive integer, traverse from small to large in order. If the positive integer values ​​of the tabIndex properties of two elements are the same, they are traversed in the order of appearance. After traversing all elements whose tabIndex is a positive integer, then traverse all elements whose tabIndex is equal to 0, or whose attribute value is an illegal value, or which does not have a tabIndex attribute, in the order in which they appear in the web page.

(8)Element.title

The Element.title attribute is used to read and write the HTML attribute title of the current element. This attribute is usually used to specify the text prompt box that pops up when the mouse is hovering.

Relevant attributes of element state

(1)Element.hidden

The Element.hidden property returns a boolean value representing the hidden property of the current element, which is used to control whether the current element is visible. This attribute can be read and written.

var btn = document.getElementById("btn");
var mydiv = document.getElementById("mydiv");

btn.addEventListener(
  "click",
  function () {
    mydiv.hidden = !mydiv.hidden;
  },
  false
);

Note that this property and CSS settings are independent of each other. The CSS setting for the visibility of this element, Element.hidden does not reflect it. In other words, this attribute cannot be used to determine the actual visibility of the current element.

The CSS setting is higher than Element.hidden. If CSS specifies that the element is invisible (display: none) or visible (display: hidden), then Element.hidden cannot change the actual visibility of the element. In other words, this property is only valid when CSS does not explicitly set the visibility of the current element.

(2)Element.contentEditable,Element.isContentEditable

HTML elements can set the contentEditable attribute to make the content of the element editable.

<div contenteditable>123</div>

In the above code, the <div> element has the contenteditable attribute, so the user can edit the content of this block on the web page.

The Element.contentEditable property returns a string indicating whether the contenteditable property is set. There are three possible values. The attribute can be written.

-"true": element content can be edited -"false": The content of the element cannot be edited -"inherit": Whether the element is editable, inheriting the settings of the parent element

The Element.isContentEditable property returns a boolean value, which also indicates whether the contenteditable property is set. This attribute is read-only.

Element.attributes

The Element.attributes property returns an object similar to an array. The members are all the attribute nodes of the current element node. For details, see the chapter "Operation of Attributes".

var p = document.querySelector("p");
var attrs = p.attributes;

for (var i = attrs.length - 1; i >= 0; i--) {
  console.log(attrs[i].name + "->" + attrs[i].value);
}

The above code traverses all the attributes of the p element.

Element.className,Element.classList

The className attribute is used to read and write the class attribute of the current element node. Its value is a string, separated by spaces between each class.

The classList property returns an array-like object, and each class of the current element node is a member of this object.

// HTML 代码 <div class="one two three" id="myDiv"></div>
var div = document.getElementById("myDiv");

div.className;
// "one two three"

div.classList;
// {
//   0: "one"
//   1: "two"
//   2: "three"
//   length: 3
// }

In the above code, the className property returns a space-separated string, and the classList property points to an array-like object. The length property (read-only) of this object returns the number of class of the current element.

The classList object has the following methods.

-add(): Add a class. -remove(): Remove a class. -contains(): Check whether the current element contains a certain class. -toggle(): Move a certain class into or out of the current element. -item(): Returns the class at the specified index position. -toString(): Convert the list of classes to strings.

var div = document.getElementById("myDiv");

div.classList.add("myCssClass");
div.classList.add("foo", "bar");
div.classList.remove("myCssClass");
div.classList.toggle("myCssClass"); // add if myCssClass does not exist, otherwise remove
div.classList.contains("myCssClass"); // return true or false
div.classList.item(0); // return the first Class
div.classList.toString();

Let's compare the writing of className and classList when adding and deleting a class.

var foo = document.getElementById("foo");

// add class
foo.className += "bold";
foo.classList.add("bold");

// delete class
foo.classList.remove("bold");
foo.className = foo.className.replace(/^bold$/, "");

The toggle method can accept a boolean value as the second parameter. If it is true, the attribute is added; if it is false, the attribute is removed.

el.classList.toggle("abc", boolValue);

// Equivalent to
if (boolValue) {
  el.classList.add("abc");
} else {
  el.classList.remove("abc");
}

Element.dataset

Web page elements can customize the data- attribute to add data.

<div data-timestamp="1522907809292"></div>

In the above code, the <div> element has a custom data-timestamp attribute, which is used to add a timestamp to the element.

The Element.dataset property returns an object from which the data- property can be read and written.

// <article
//   id="foo"
//   data-columns="3"
//   data-index-number="12314"
//   data-parent="cars">
//   ...
// </article>
var article = document.getElementById("foo");
article.dataset.columns; // "3"
article.dataset.indexNumber; // "12314"
article.dataset.parent; // "cars"

Note that all the attributes returned in dataset are all strings.

In the HTML code, the attribute name of the data- attribute can only contain English letters, numbers, conjunction lines (-), dots (.), colons (:) and underscores (_). They are converted into JavaScript corresponding dataset property names, the rules are as follows.

-The first data- will be omitted. -If the conjunction line is followed by an English letter, the conjunction line will be cancelled and the letter will be capitalized. -Other characters remain unchanged.

Therefore, data-abc-def corresponds to dataset.abcDef, and data-abc-1 corresponds to dataset["abc-1"].

In addition to using dataset to read and write data- attributes, you can also use Element.getAttribute() and Element.setAttribute() to read and write these attributes through the complete attribute name.

var mydiv = document.getElementById("mydiv");

mydiv.dataset.foo = "bar";
mydiv.getAttribute("data-foo"); // "bar"

Element.innerHTML

The Element.innerHTML property returns a string, which is equivalent to all the HTML code contained in the element. This attribute is readable and writable, and is often used to set the content of a node. It can rewrite the content of all element nodes, including <HTML> and <body> elements.

If the innerHTML attribute is set to empty, it is equivalent to deleting all the nodes it contains.

el.innerHTML = "";

The above code is equivalent to turning the el node into an empty node, and all the nodes originally contained in el are deleted.

Note that when reading the attribute value, if the text node contains &, less than sign (<) and greater than sign (>), the innerHTML attribute will convert them into entity form &, <, >. If you want to get the original text, it is recommended to use the element.textContent property.

// The HTML code is as follows<p id="para"> 5> 3 </p>
document.getElementById("para").innerHTML;
// 5 &gt; 3

When writing, if the inserted text contains HTML tags, it will be parsed into a node object and inserted into the DOM. Note that if the text contains the <script> tag, although the script node can be generated, the inserted code will not be executed.

var name = "<script>alert('haha')</script>";
el.innerHTML = name;

The above code inserts the script into the content, but the script will not be executed. However, innerHTML still has security risks.

var name = "<img src=x onerror=alert(1)>";
el.innerHTML = name;

In the above code, the alert method will be executed. Therefore, for safety reasons, if you insert text, it is best to use the textContent attribute instead of innerHTML.

Element.outerHTML

The Element.outerHTML property returns a string that represents all the HTML code of the current element node, including the element itself and all child elements.

// HTML code is as follows
// <div id="d"><p>Hello</p></div>
var d = document.getElementById("d");
d.outerHTML;
// '<div id="d"><p>Hello</p></div>'

The outerHTML attribute is readable and writable. Assigning a value to it is equivalent to replacing the current element.

// HTML code is as follows
// <div id="container"><div id="d">Hello</div></div>
var container = document.getElementById("container");
var d = document.getElementById("d");
container.firstChild.nodeName; // "DIV"
d.nodeName; // "DIV"

d.outerHTML = "<p>Hello</p>";
container.firstChild.nodeName; // "P"
d.nodeName; // "DIV"

In the above code, the variable d represents the child node. After its outerHTML attribute is re-assigned, the inner div element does not exist and is replaced by the p element. However, the variable d still points to the original div element, which means that the replaced DIV element still exists in memory.

Note that if a node does not have a parent node, setting the outerHTML attribute will report an error.

var div = document.createElement("div");
div.outerHTML = "<p>test</p>";
// DOMException: This element has no parent node.

In the above code, the div element has no parent node, and an error will be reported when the outerHTML attribute is set.

Element.clientHeight,Element.clientWidth

The Element.clientHeight property returns an integer value, which represents the CSS height of the element node (in pixels), which is only valid for block-level elements, and returns 0 for inline elements. If the CSS height is not set for the block-level element, the actual height is returned.

In addition to the height of the element itself, it also includes the padding part, but not border, margin. If there is a horizontal scroll bar, also subtract the height of the horizontal scroll bar. Note that this value is always an integer, if it is a decimal, it will be rounded.

The Element.clientWidth property returns the CSS width of the element node, which is also only valid for block-level elements, and only includes the width of the element itself and padding. If there is a vertical scroll bar, the width of the vertical scroll bar is also subtracted.

The clientHeight property of document.documentElement returns the height of the current viewport (that is, the height of the browser window), which is equivalent to the window.innerHeight property minus the height of the horizontal scroll bar (if any). The height of document.body is the actual height of the web page. Generally speaking, document.body.clientHeight is greater than document.documentElement.clientHeight.

// Viewport height
document.documentElement.clientHeight;

// Total height of the page
document.body.clientHeight;

Element.clientLeft,Element.clientTop

The Element.clientLeft property is equal to the width (in pixels) of the left border of the element node, excluding the padding and margin on the left. If the left border is not set, or if it is an inline element (display: inline), this property returns 0. This attribute always returns an integer value, if it is a decimal, it will be rounded.

The Element.clientTop property is equal to the width (in pixels) of the top border of the web page element, and other features are the same as clientLeft.

Element.scrollHeight,Element.scrollWidth

The Element.scrollHeight property returns an integer value (decimals will be rounded off), which represents the total height (unit pixel) of the current element, including the overflow container and the currently invisible part. It includes padding, but does not include border, margin and the height of the horizontal scroll bar (if there is a horizontal scroll bar), and also includes the height of pseudo elements (::before or ::after) .

The Element.scrollWidth property represents the total width (in pixels) of the current element, and other places are similar to the scrollHeight property. These two attributes are read-only.

The total height of the entire web page can be read from document.documentElement or document.body.

// Return the total height of the page
document.documentElement.scrollHeight;
document.body.scrollHeight;

Note that if the content of the element node overflows, even if the overflowed content is hidden, the scrollHeight property still returns the total height of the element.

// HTML code is as follows
// <div id="myDiv" style="height: 200px; overflow: hidden;">...<div>
document.getElementById("myDiv").scrollHeight; // 356

In the above code, even though the CSS height of the myDiv element is only 200 pixels, and the overflow part is not visible, the scrollHeight will still return the original height of the element.

Element.scrollLeft,Element.scrollTop

The Element.scrollLeft property represents the number of pixels by which the horizontal scroll bar of the current element scrolls to the right, and the Element.scrollTop property represents the number of pixels by which the vertical scroll bar of the current element scrolls down. For those web page elements without scroll bars, these two attributes are always equal to 0.

If you want to view the horizontal and vertical scrolling distance of the entire web page, you must read it from the document.documentElement element.

document.documentElement.scrollLeft;
document.documentElement.scrollTop;

Both of these attributes are readable and writable. Setting the value of this attribute will cause the browser to automatically scroll the current element to the corresponding position.

Element.offsetParent

The Element.offsetParent property returns the upper element that is closest to the current element and whose CSS position property is not equal to static.

<div style="position: absolute;">
  <p>
    <span>Hello</span>
  </p>
</div>

In the above code, the offsetParent attribute of the span element is the div element.

This attribute is mainly used to determine the calculation basis for the offset of the child element. Element.offsetTop and Element.offsetLeft are calculated by the offsetParent element.

If the element is invisible (the display property is none), or the position is fixed (the position property is fixed), the offsetParent property returns null.

<div style="position: absolute;">
  <p>
    <span style="display: none;">Hello</span>
  </p>
</div>

In the above code, the offsetParent attribute of the span element is null.

If the position property of all upper nodes of an element is static, the Element.offsetParent property points to the <body> element.

Element.offsetHeight,Element.offsetWidth

The Element.offsetHeight property returns an integer that represents the CSS vertical height (in pixels) of the element, including the height of the element itself, padding and border, and the height of the horizontal scroll bar (if there is a scroll bar).

The Element.offsetWidth property represents the CSS horizontal width (in pixels) of the element, and everything else is consistent with Element.offsetHeight.

These two properties are read-only properties, and only have the height or width of the border more than Element.clientHeight and Element.clientWidth. If the CSS of the element is set to invisible (such as display: none;), then 0 is returned.

Element.offsetLeft,Element.offsetTop

Element.offsetLeft returns the horizontal displacement of the upper left corner of the current element relative to the Element.offsetParent node, and Element.offsetTop returns the vertical displacement in pixels. Usually, these two values ​​refer to the displacement relative to the parent node.

The following code can calculate the coordinates of the upper left corner of the element relative to the entire web page.

function getElementPosition(e) {
  var x = 0;
  var y = 0;
  while (e !== null)  {
    x += e.offsetLeft;
    y + = e.offsetTop;
    e = e.offsetParent;
  }
  return {x: x, y: y};
}

Element.style

Each element node has style to read and write the inline style information of the element. For details, please refer to the chapter "CSS Operation".

Element.children,Element.childElementCount

The Element.children property returns an array-like object (HTMLCollection instance), including all child elements of the current element node. If the current element has no child elements, the returned object contains zero members.

if (para.children.length) {
  var children = para.children;
  for (var i = 0; i < children.length; i++) {
    // ...
  }
}

The above code traverses all the child elements of the para element.

The difference between this attribute and the Node.childNodes attribute is that it only includes the child nodes of the element type, and does not include other types of child nodes.

The Element.childElementCount property returns the number of child element nodes contained in the current element node, which is the same as the value of Element.children.length.

Element.firstElementChild,Element.lastElementChild

The Element.firstElementChild property returns the first element child node of the current element, and Element.lastElementChild returns the last element child node.

If there are no element child nodes, these two attributes return null.

Element.nextElementSibling,Element.previousElementSibling

The Element.nextElementSibling property returns the next sibling element node of the current element node, or null if there is none.

// HTML code is as follows
// <div id="div-01">Here is div-01</div>
// <div id="div-02">Here is div-02</div>
var el = document.getElementById("div-01");
el.nextElementSibling;
// <div id="div-02">Here is div-02</div>

The Element.previousElementSibling property returns the previous sibling element node of the current element node, or null if there is no element node.

Example method

The element node provides six methods to manipulate attributes.

-getAttribute(): read the value of an attribute -getAttributeNames(): return all attribute names of the current element -setAttribute(): write attribute value -hasAttribute(): Does an attribute exist -hasAttributes(): whether the current element has attributes -removeAttribute(): delete attribute

For the introduction of these methods, please see the chapter "Operation of Attributes".

Element.querySelector()

The Element.querySelector method accepts a CSS selector as a parameter and returns the first matching child element of the parent element. If no matching child element is found, null is returned.

var content = document.getElementById("content");
var el = content.querySelector("p");

The above code returns the first p element of the content node.

The Element.querySelector method can accept any complex CSS selector.

document.body.querySelector("style[type='text/css'], style:not([type])");

Note that this method cannot select pseudo-elements.

It can accept multiple selectors, separated by commas.

element.querySelector("div, p");

The above code returns the first div or p child element of element.

It should be noted that when the browser executes the querySelector method, it first searches for the given CSS selector in the global scope, and then filters out which child elements belong to the current element. Therefore, there will be some counter-intuitive results. Below is a piece of HTML code.

<div>
  <blockquote id="outer">
    <p>Hello</p>
    <div id="inner">
      <p>World</p>
    </div>
  </blockquote>
</div>

So, if you query like the following, the first p element is actually returned instead of the second.

var outer = document.getElementById("outer");
outer.querySelector("div p");
// <p>Hello</p>

Element.querySelectorAll()

The Element.querySelectorAll method accepts a CSS selector as a parameter, and returns a NodeList instance containing all matching child elements.

var el = document.querySelector("# test");
var matches = el.querySelectorAll("div.highlighted > p");

The execution mechanism of this method is the same as that of the querySelector method. It also searches in the global scope first, and then filters out the child elements of the current element. Therefore, the selector is actually for the entire document.

It can also accept multiple CSS selectors, separated by commas. If there is a pseudo-element selector in the selector, an empty NodeList instance is always returned.

Element.getElementsByClassName()

The Element.getElementsByClassName method returns an HTMLCollection instance, the members are all child element nodes of the current element node with the specified class. This method is similar to the usage of the document.getElementsByClassName method, except that the search scope is not the entire document, but the current element node.

element.getElementsByClassName("red test");

Note that the parameters of this method are case sensitive.

Since the HTMLCollection instance is a living collection, any changes in the document object will be reflected in the instance immediately, and the following code will not take effect.

// HTML code is as follows
// <div id="example">
//   <p class="foo"></p>
//   <p class="foo"></p>
// </div>
var element = document.getElementById("example");
var matches = element.getElementsByClassName("foo");

for (var i = 0; i < matches.length; i++) {
  matches[i].classList.remove("foo");
  matches.item(i).classList.add("bar");
}
// After execution, the HTML code is as follows
// <div id="example">
//   <p></p>
//   <p class="foo bar"></p>
// </div>

In the above code, once the first member of the matches set is removed from the class foo, it will immediately disappear from the matches, resulting in the above result.

Element.getElementsByTagName()

The Element.getElementsByTagName() method returns an instance of HTMLCollection. The members are all child element nodes of the current node that match the specified tag name. This method is similar to the usage of the document.getElementsByClassName() method, except that the search scope is not the entire document, but the current element node.

var table = document.getElementById("forecast-table");
var cells = table.getElementsByTagName("td");

Note that the parameters of this method are case-insensitive, because HTML tag names are also case-insensitive.

Element.closest()

The Element.closest method accepts a CSS selector as a parameter, and returns an ancestor node (including the current node itself) that matches the selector and is closest to the current node. If no node matches the CSS selector, null is returned.

// HTML code is as follows
// <article>
//   <div id="div-01">Here is div-01
//     <div id="div-02">Here is div-02
//       <div id="div-03">Here is div-03</div>
//     </div>
//   </div>
// </article>

var div03 = document.getElementById("div-03");

// div-03 nearest ancestor node
div03.closest("#div-02"); // div-02
div03.closest("div div"); // div-03
div03.closest("article > div"); //div-01
div03.closest(":not(div)"); // article

In the above code, because the closest method also takes the current node into account, the second closest method returns div-03.

Element.matches()

The Element.matches method returns a boolean value indicating whether the current element matches the given CSS selector.

if (el.matches(".someClass")) {
  console.log("Match!");
}

The following three methods are related to the events of the Element node. These methods are inherited from the EventTarget interface, see the relevant chapters for details.

-Element.addEventListener(): add event callback function -Element.removeEventListener(): Remove event listener function -Element.dispatchEvent(): trigger event

element.addEventListener("click", listener, false);
element.removeEventListener("click", listener, false);

var event = new Event("click");
element.dispatchEvent(event);

Element.scrollIntoView()

The Element.scrollIntoView method scrolls the current element and enters the visible area of ​​the browser, similar to the effect of setting window.location.hash.

el.scrollIntoView(); // equivalent to el.scrollIntoView(true)
el.scrollIntoView(false);

This method can accept a Boolean value as a parameter. If it is true, it means that the top of the element is aligned with the top of the visible part of the current area (provided that the current area is scrollable); if it is false, it means that the bottom of the element is aligned with the end of the visible part of the current area (provided that The current area can be scrolled). If this parameter is not provided, it defaults to true.

Element.getBoundingClientRect()

The Element.getBoundingClientRect method returns an object that provides information such as the size and position of the current element node, which is basically all the information of the CSS box model.

var rect = obj.getBoundingClientRect();

In the above code, the rect object returned by the getBoundingClientRect method has the following properties (all are read-only).

-x: the abscissa of the upper left corner of the element relative to the viewport -y: the ordinate of the upper left corner of the element relative to the viewport -height: element height -width: element width -left: The abscissa of the upper left corner of the element relative to the viewport, which is equal to the x property -right: the abscissa of the right boundary of the element relative to the viewport (equal to x + width) -top: the ordinate of the top of the element relative to the viewport, which is equal to the y attribute -bottom: the ordinate of the bottom of the element relative to the viewport (equal to y + height)

Since the position of the element relative to the viewport will change as the page scrolls, the four attribute values ​​indicating the position are not fixed. If you want to get the absolute position, you can add window.scrollX to the left property, and window.scrollY to the top property.

Note that all properties of the getBoundingClientRect method count the border (the border property) as part of the element. In other words, it is calculated from various points on the outer edge of the frame. Therefore, width and height include the element itself + padding + border.

In addition, the above attributes are all inherited from the prototype, and Object.keys will return an empty array. This also requires attention.

var rect = document.body.getBoundingClientRect();
Object.keys(rect); // []

In the above code, the rect object does not have its own properties, and the Object.keys method only returns the properties of the object itself, so an empty array is returned.

Element.getClientRects()

The Element.getClientRects method returns an array-like object, which contains all the rectangles formed by the current element on the page (so the Rect in the method name is plural). Each rectangle has six properties: bottom, height, left, right, top and width, which represent their four coordinates relative to the viewport, as well as their own height and width.

For box elements (such as <div> and <p>), there is only one member of the element in the object returned by this method. For inline elements (such as <span>, <a>, <em>), the number of members in the object returned by this method depends on how many lines the element occupies on the page. This is the main difference between it and the Element.getBoundingClientRect() method, which always returns a rectangle for inline elements.

<span id="inline">Hello World Hello World Hello World</span>

The above code is an inline element <span>. If it occupies three lines on the page, the object returned by the getClientRects method has three members. If it occupies one line on the page, the object returned by the getClientRects method is only One member.

var el = document.getElementById("inline");
el.getClientRects().length; // 3
el.getClientRects()[0].left; // 8
el.getClientRects()[0].right; // 113.908203125
el.getClientRects()[0].bottom; // 31.200000762939453
el.getClientRects()[0].height; // 23.200000762939453
el.getClientRects()[0].width; // 105.908203125

This method is mainly used to determine whether the elements in the line wrap, and the position offset of each line of the elements in the line.

Note that if the inline element includes a newline character, then this method will take the newline character into account.

<span id="inline"> Hello World Hello World Hello World </span>

In the above code, there are three newline characters inside the <span> node. Even if the HTML language ignores the newline characters and displays them as one line, the getClientRects() method will still return three members. If the line width is set very narrow, the above <span> element is displayed as 6 lines, then six members will be returned.

Element.insertAdjacentElement()

The Element.insertAdjacentElement method inserts a new node at the specified position relative to the current element. This method returns the inserted node, if the insertion fails, it returns null.

element.insertAdjacentElement(position, element);

The Element.insertAdjacentElement method can accept two parameters in total. The first parameter is a string indicating the position of insertion, and the second parameter is the node to be inserted. The first parameter can only take the following values.

-beforebegin: before the current element -afterbegin: before the first child node inside the current element -beforeend: after the last child node inside the current element -afterend: after the current element

Note that the two values ​​of beforebegin and afterend will only take effect when the current node has a parent node. If the current node is created by the script and has no parent node, then the insertion will fail.

var p1 = document.createElement("p");
var p2 = document.createElement("p");
p1.insertAdjacentElement("afterend", p2); // null

In the above code, p1 has no parent node, so inserting p2 after it fails.

If the inserted node is an existing node in the document, it will be deleted from its original position and placed in a new position.

Element.insertAdjacentHTML(),Element.insertAdjacentText()

The Element.insertAdjacentHTML method is used to parse an HTML string to generate a DOM structure and insert it at a specified position relative to the current node.

element.insertAdjacentHTML(position, text);

This method accepts two parameters, the first is a string representing the specified position, and the second is the HTML string to be parsed. The first parameter can only set one of the following four values.

-beforebegin: before the current element -afterbegin: before the first child node inside the current element -beforeend: after the last child node inside the current element -afterend: after the current element

// HTML 代码:<div id="one">one</div>
var d1 = document.getElementById("one");
d1.insertAdjacentHTML("afterend", '<div id="two">two</div>');
// HTML code after execution:
// <div id="one">one</div><div id="two">two</div>

This method just inserts nodes into the existing DOM structure, which makes its execution speed much faster than the innerHTML method.

Note that this method will not escape the HTML string, which makes it unable to be used to insert the content entered by the user, otherwise there will be a security risk.

The Element.insertAdjacentText method inserts a text node at a specified position relative to the current node. The usage is exactly the same as the Element.insertAdjacentHTML method.

// HTML 代码:<div id="one">one</div>
var d1 = document.getElementById("one");
d1.insertAdjacentText("afterend", "two");
// HTML code after execution:
// <div id="one">one</div>two

Element.remove()

The Element.remove method inherits from the ChildNode interface and is used to remove the current element node from its parent node.

var el = document.getElementById("mydiv");
el.remove();

The above code removes the el node from the DOM tree.

Element.focus(),Element.blur()

The Element.focus method is used to shift the focus of the current page to the specified element.

document.getElementById("my-span").focus();

This method can accept an object as a parameter. The preventScroll property of the parameter object is a boolean value that specifies whether to keep the current element at the original position instead of scrolling to the visible area.

function getFocus() {
  document.getElementById("btn").focus({ preventScroll: false });
}

The above code will make the btn element get the focus and scroll to the visible area.

Finally, you can get the currently focused element from the document.activeElement property.

The Element.blur method is used to remove the focus from the current element.

Element.click()

The Element.click method is used to simulate a mouse click on the current element, which is equivalent to triggering the click event.