因此,如果我有以下HTML:
<div id='div'>
<a>Link</a>
<span>text</span>
</div>
我该如何使用JavaScript在空白行处添加HTML元素?
因此,如果我有以下HTML:
<div id='div'>
<a>Link</a>
<span>text</span>
</div>
我该如何使用JavaScript在空白行处添加HTML元素?
node = document.getElementById('YourID');
node.insertAdjacentHTML('afterend', '<div>Sample Div</div>');
可用选项
beforebegin,afterbegin,beforeend,afterend
因为您没有提到使用任何 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);
document.getElementById('#div')
将会是 null,你可能想要使用 document.getElementById('div')
。 - Daniel VandersluisparentElement.insertBefore(newElement, childElement)
。 - Andy EinsertAfter
并不是一个真正的函数。 - Daniel Vandersluis与其他答案不同,如果你知道你总是想在<a>
元素之后插入,而不是处理<div>
的子元素,请给它一个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);
}
这将允许您始终保证新元素遵循链接。
如果你想使用类似于jQuery的东西,你可以这样做:
$('#div a').after("Your html element");
jQuery有一个很好的内置函数可以做到这一点:after(),请查看http://api.jquery.com/after/
在你的情况下,你可能需要使用这样的选择器:
$('#div a').after('<p>html element to add</p>');
如果您不熟悉jQuery,上面链接中的代码示例还展示了如何加载jQuery。
Element#after
可以用于在某个 HTML 元素之后直接插入元素。
例如:
document.querySelector("#div > a").after(
Object.assign(document.createElement('div'), {textContent: 'test', style: 'border: 1px solid'}));
<div id='div'>
<a>Link</a>
<span>text</span>
</div>
假设你只添加一个元素:
document.getElementById("div").insertBefore({Element}, document.getElementById("div").children[2]);