Вместо того, чтобы обращаться с потомками <div>
, как и в других ответах, если вы знаете, что всегда хотите вставить после элемента <a>
, присвойте ему идентификатор, а затем вы можете вставить относительно его братьев и сестер:
<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);
}
Это позволит вам всегда гарантировать, что ваш новый элемент будет следовать по ссылке.