If i have an HTML element like
Something like this should do it:
<script type="text/javascript">
var parent = document.getElementById('parentDiv');
var sibling = document.getElementById('childDiv');
var text = document.createTextNode('new text');
parent.insertBefore(text, sibling);
</script>
Just for the record:
div.insertAdjacentHTML( 'beforeBegin', yourText );
where div
is your child-DIV.
Live demo: http://jsfiddle.net/ZkzDk/
You can add text node. Create node - document.createTextNode('text')
and then insert/append/replace - do whatever you want.
In regards to the topic and the users question for inserting before or after, here is an example for after:
var text = document.createTextNode("my text must be added here.");
var childTag = document.getElementById("childDiv");
childTag.parentNode.insertBefore(text, childTag.nextSibling);
If the childTag does not have any siblings, it is okay because the insertBefore method handles this case and simply adds it as the last child.
Also can possibly use the appendChild() method after creating text node then add your childTag via the parentNode.
If you just need text, I find that element.insertAdjacentText(position, text) is flexible for many scenarios and is also compatible with older browsers like IE6. Where position
is exactly where you want the text to be and text
is the text node or just a string. The options are:
'beforebegin'
Before the element itself.'afterbegin'
Just inside the element, before its first child.'beforeend'
Just inside the element, after its last child.'afterend'
After the element itself.Like this:
let div = document.getElementById('parentDiv');
div.insertAdjacentText('afterbegin', 'My Plain Text..');
Yes, you can create a text node with document.createTextNode('the text')
Then you can insert it like an element, with appendChild or insertBefore.
Example that insert a text before #childDiv:
var text = document.createTextNode('the text');
var child = document.getElementById('childDiv');
child.parentNode.insertBefore(text, child);