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?
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.
The insertBefore() method inserts HTML elements before the selected elements. Tip: To insert HTML elements after the selected elements, use the insertAfter() method.
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.
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.
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);
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