使用JavaScript添加HTML元素

Joh*_*mac 9 html javascript dom

所以,如果我有这样的HTML:

<div id='div'>
  <a>Link</a>

  <span>text</span>
</div>
Run Code Online (Sandbox Code Playgroud)

如何使用JavaScript在空白行的位置添加HTML元素?

Saq*_* R. 17

node = document.getElementById('YourID');
node.insertAdjacentHTML('afterend', '<div>Sample Div</div>');
Run Code Online (Sandbox Code Playgroud)

可用选项

beforebegin,afterbegin,beforeend,afterend


Dan*_*uis 6

<div>其他答案一样处理孩子,如果你知道你总是想在<a>元素之后插入,给它一个ID,然后你可以相对于它的兄弟姐妹插入:

<div id="div">
  <a id="div_link">Link</a>

  <span>text</span>
</div>
Run Code Online (Sandbox Code Playgroud)

然后在该元素后面直接插入新元素:

var el = document.createElement(element_type); // where element_type is the tag name you want to insert
// ... set element properties as necessary

var div = document.getElementById('div');
var div_link = document.getElementById('div_link');
var next_sib = div_link.nextSibling;

if (next_sib)
{
  // if the div_link has another element following it within the link, insert
  // before that following element
  div.insertBefore(el, next_sib);
}
else
{
  // otherwise, the link is the last element in your div,
  // so just append to the end of the div
  div.appendChild(el);
}
Run Code Online (Sandbox Code Playgroud)

这将允许您始终保证您的新元素遵循链接.


sim*_*rsh 5

正如您没有提到对javascript库(如jquery,dojo)的任何使用一样,这里有一些纯JavaScript。

var txt = document.createTextNode(" This text was added to the DIV.");
var parent = document.getElementById('div');
parent.insertBefore(txt, parent.lastChild);
Run Code Online (Sandbox Code Playgroud)

要么

var link = document.createElement('a');
link.setAttribute('href', 'mypage.htm');
var parent = document.getElementById('div');
parent.insertAfter(link, parent.firstChild);
Run Code Online (Sandbox Code Playgroud)

  • “ insertAfter”也不是实际函数。 (8认同)
  • 这是不正确的。* insertBefore *不是全局函数,它是* HTMLElement *原型上的方法。正确的方法是“ parentElement.insertBefore(newElement,childElement)”。 (2认同)