6

What is the equivalent of .before() in Javascript?

apaul
  • 16,092
  • 8
  • 47
  • 82
Akos
  • 1,997
  • 6
  • 27
  • 40

3 Answers3

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