How to insert HTML before element in JavaScript without jQuery? [closed]
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);
You can make your own function in javascript like,
Code
var id = document.getElementById('my_id');
var s = document.createElement('span');
s.innerHTML = '*';
s.className = 'asterisk';
id.parentNode.insertBefore(s, id);
InsertBefore Docs and Example
You can create a function before like,
before: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
source from http://code.jquery.com/jquery-1.9.1.js