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
与<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)
这将允许您始终保证您的新元素遵循链接.
正如您没有提到对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)
| 归档时间: |
|
| 查看次数: |
29681 次 |
| 最近记录: |