所以,如果我有HTML這樣的:添加HTML元素的JavaScript
<div id='div'>
<a>Link</a>
<span>text</span>
</div>
如何使用JavaScript來添加一個HTML元素,其中空白行?
所以,如果我有HTML這樣的:添加HTML元素的JavaScript
<div id='div'>
<a>Link</a>
<span>text</span>
</div>
如何使用JavaScript來添加一個HTML元素,其中空白行?
當你沒有提及任何使用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);
編碼愉快。
如果你想使用類似的jQuery你可以做這樣的事情:
$('#div a').after("Your html element");
jQuery有一個不錯的,內置的功能是:()之後,在http://api.jquery.com/after/
在你的情況,你可能會想選擇這樣的:
$('#div a').after('<p>html element to add</p>');
從的代碼示例上面給出的鏈接也顯示如何加載jQuery,如果這對你來說是新的。
假設你只需要添加一個元素:
document.getElementById("div").insertBefore({Element}, document.getElementById("div").children[2]);
而是與<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);
}
這將允許您始終保證您的新元素遵循鏈接。
node = document.getElementById('YourID');
node.insertAdjacentHTML('afterend', '<div>Sample Div</div>');
可選項
beforebegin,afterbegin,beforeend,afterend
這也有相當不錯的瀏覽器支持。如果你不打算在舊的IE和桌子結合使用它。 http://caniuse.com/#feat=insertadjacenthtml – cptnk 2017-03-06 12:00:46
'的document.getElementById( '#DIV')'將是空的,你可能是指'文件。 getElementById('div')' – 2010-08-06 15:27:07
這是不正確的。 * insertBefore *不是全局函數,它是* HTMLElement *原型中的一個方法。正確的方法是'parentElement.insertBefore(newElement,childElement)'。 – 2010-08-06 15:28:19
啊,我的不好。謝謝。 – simplyharsh 2010-08-06 15:29:08