close

轉自 https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

--

The insertAdjacentHTML() method parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It does not reparse the element it is being used on, and thus it does not corrupt the existing elements inside that element. This avoids the extra step of serialization, making it much faster than direct innerHTMLmanipulation.

SyntaxSection

element.insertAdjacentHTML(position, text);

ParametersSection

position
DOMString representing the position relative to the element; must be one of the following strings:
  • 'beforebegin': Before the element itself.
  • 'afterbegin': Just inside the element, before its first child.
  • 'beforeend': Just inside the element, after its last child.
  • 'afterend': After the element itself.
text
text is the string to be parsed as HTML or XML and inserted into the tree.

Visualization of position namesSection

<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->
Note: The beforebegin and afterend positions work only if the node is in the DOM tree and has a parent element.

ExampleSection

// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>

NotesSection

Security ConsiderationsSection

When inserting HTML into a page by using insertAdjacentHTML be careful not to use user input that hasn't been escaped.

It is not recommended you use insertAdjacentHTML when inserting plain text; instead, use the Node.textContent property or Element.insertAdjacentText() method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.

SpecificationSection

SpecificationStatusComment
DOM Parsing and Serialization
The definition of 'Element.insertAdjacentHTML()' in that specification.
Working Draft  

Browser compatibilitySection

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung Internet
Basic support Full support1 Full support12 Full support8 Full support7 Full support4 Full support2.3 Full support18 Full support12 Full support8 Full supportYes Full support4 Full supportYes

Legend

Full support 
Full support
See implementation notes.
See implementation notes.

See alsoSection

--

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 dizzy03 的頭像
    dizzy03

    碎碎念

    dizzy03 發表在 痞客邦 留言(0) 人氣()