Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add text before or after an HTML element

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>
like image 675
John Avatar asked Sep 11 '11 12:09

John


People also ask

How do I put HTML before an element?

The insertBefore() method inserts HTML elements before the selected elements. Tip: To insert HTML elements after the selected elements, use the insertAfter() method.

What is the correct syntax to insert content after the div elements?

The jQuery after() method is used to insert content after the selected elements.

How do you add text in HTML CSS?

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.

Is there insert after in JavaScript?

The insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.


3 Answers

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); 
like image 75
Arnaud Le Blanc Avatar answered Oct 14 '22 16:10

Arnaud Le Blanc


Just for the record:

div.insertAdjacentHTML( 'beforeBegin', yourText );

where div is your child-DIV.

Live demo: http://jsfiddle.net/ZkzDk/

like image 20
Šime Vidas Avatar answered Oct 14 '22 14:10

Šime Vidas


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..');
like image 20
Juan Marco Avatar answered Oct 14 '22 14:10

Juan Marco