If i have an HTML element like <div>
with some text inside or another elements can I add before or after this div some text data without an html element, just plain text?
I'd like to use only pure Javascript.
Something like :
<div id="parentDiv">
my text must be added here
<div id="childDiv"></div>
</div>
The insertBefore() method inserts HTML elements before the selected elements. Tip: To insert HTML elements after the selected elements, use the insertAfter() method.
The jQuery after() method is used to insert content after the selected elements.
CSS can insert text content before or after an element. To specify this, make a rule and add ::before or ::after to the selector. In the declaration, specify the content property with the text content as its value.
The insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.
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);
Just for the record:
div.insertAdjacentHTML( 'beforeBegin', yourText );
where div
is your child-DIV.
Live demo: http://jsfiddle.net/ZkzDk/
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..');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With