使用JavaScript添加HTML元素

时间:2010-08-06 15:15:00

标签: javascript html dom

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

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

  <span>text</span>
</div>

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

6 个答案:

答案 0 :(得分:12)

node = document.getElementById('YourID');
node.insertAdjacentHTML('afterend', '<div>Sample Div</div>');

可用选项

  

beforebegin,afterbegin,beforeend,afterend

答案 1 :(得分:6)

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

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

  <span>text</span>
</div>

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

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);
}

这将允许您始终保证您的新元素在链接之后。

答案 2 :(得分:4)

由于你没有提到使用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);

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

答案 3 :(得分:2)

如果你想使用像jQuery这样的东西,你可以这样做:

$('#div a').after("Your html element");

答案 4 :(得分:2)

jQuery有一个很好的内置函数:after(),http://api.jquery.com/after/

在您的情况下,您可能需要这样的选择器:

$('#div a').after('<p>html element to add</p>');

上面给出的链接中的代码示例还显示了如果对您来说是新的加载jQuery。

答案 5 :(得分:0)

假设您只添加一个元素:

document.getElementById("div").insertBefore({Element}, document.getElementById("div").children[2]);
相关问题