What is the equivalent of .before() in Javascript?
Asked
Active
Viewed 3,566 times
6
-
4In its simplest form, `a.before(b)` is `a.parentNode.insertBefore(b,a)` – Niet the Dark Absol Mar 14 '14 at 13:50
-
2[MDN: Node.insertBefore(newElement, referenceElement)](https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore) – t.niese Mar 14 '14 at 13:51
-
3You can always look at [the source](http://code.jquery.com/jquery-1.11.0.js) – Jason P Mar 14 '14 at 13:51
-
I believe you mean `.insertbefore()` – rolory Mar 14 '14 at 13:51
-
2@NiettheDarkAbsol you should post that as an answer. – Rory McCrossan Mar 14 '14 at 13:51
-
1https://github.com/jquery/jquery/blob/a96d5bed58f2b30f97d6dd2f5691cd890f62b75f/src/manipulation.js#L342 – j08691 Mar 14 '14 at 13:53
-
Check the jquery source https://github.com/jquery/jquery/blob/a96d5bed58f2b30f97d6dd2f5691cd890f62b75f/src/manipulation.js#L342 – Aamir Afridi Mar 14 '14 at 13:53
-
Seems it is a duplicate... check @ http://stackoverflow.com/questions/19315948/insert-html-before-element-in-javascript-without-jquery – JQuery Guru Mar 14 '14 at 13:54
3 Answers
9
node.insertBefore()
is pretty much the equivalent : https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore
$('#id').before('something');
//equivalent
var node = document.getElementById('id');
node.parentNode.insertBefore('something', node);
Here what jQuery does : https://gist.github.com/kagagnon/a13de27760ba1af883c0#file-gistfile1-js-L6064
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
}

Karl-André Gagnon
- 33,662
- 5
- 50
- 75
3
you can use insertBefore
in javascript
node.insertBefore(newnode, existingchild);
The example above will append newnode as a child of node, directly before the existingchild node.

Arjit
- 3,290
- 1
- 17
- 18
0
Ok these answers were a bit deceptive. It’s a bit different using node.insertBefore
than using the jQuery .before()
method.
// jQuery
$('.element').before('<span class="class-name">Some text</span>');
// Pure JS
var _$element = document.querySelector('.element');
var _$new = document.createElement('span');
_$new.outerHTML = '<span class="class-name">Some text</span>';
_$element.parentNode.insertBefore(_$new, _$element);
If you are wondering why it looks so simple in the jQuery snippet
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
}
Well notice that it starts with this.domManip
. It is doing stuff behind the scenes in that function that abstracts away the element creation stuff.

Daniel Tonon
- 9,261
- 5
- 61
- 64