Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert HTML before element in JavaScript without jQuery? [closed]

Is there a pure JavaScript function for inserting HTML before another element? In jQuery it can be accomplished like this:

$("#my_id").before('<span class="asterisk">*</span>'); 

If there isn't any equivalent JavaScript function how can I achieve the described functionality?

like image 845
Aymand Osanes Avatar asked Oct 11 '13 10:10

Aymand Osanes


People also ask

How to add HTML before element JavaScript?

In vanilla JavaScript, you can use the insertBefore() method to insert an element before another HTML element in the DOM. This method adds an element, right before an existing element in the document.

How to append HTML before element?

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

How do you use prepend in JavaScript?

First, select the ul element by its id by using the querySelector() method. Second, declare an array of strings. Third, for each element in an array, create a new li element with the textContent is assigned to the array element. Finally, prepend the li elements to the ul parent element by using the prepend() method.


2 Answers

A little-known method is the element.insertAdjacentHTML. With this method (supported by all major browsers, including IE 4), you can take an arbitrary HTML string, and insert it anywhere in the document.

To illustrate the power of the method, let's use your example...:

$("#my_id").before('<span class="asterisk">*</span>'); 

Becomes

document.getElementById('my_id').insertAdjacentHTML('beforebegin',     '<span class="asterisk">*</span>'); 

insertAdjacentHTML's first argument determines the insertion position. Here's a comparison with jQuery:

  • $().before - 'beforebegin'
  • $().prepend - 'afterbegin'
  • $().append - 'beforeend'
  • $().insertAfter - 'afterend'

As you can see, it's very easy to use. Assuming that the jQuery selector returns only one element, you can in general use document.querySelector, but in this specific case, using document.getElementById is more efficient.

like image 158
Rob W Avatar answered Oct 08 '22 13:10

Rob W


Edit: I prefer @Rob W's answer and think that that should be the accepted answer, not this one.


This will do what you want, without needing the support of any bloated libraries like jQuery.

var my_elem = document.getElementById('my_id');  var span = document.createElement('span');     span.innerHTML = '*';     span.className = 'asterisk';  my_elem.parentNode.insertBefore(span, my_elem); 
like image 38
Codemonkey Avatar answered Oct 08 '22 11:10

Codemonkey