5

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

apaul
  • 15,894
  • 8
  • 45
  • 79
Akos
  • 1,949
  • 6
  • 27
  • 40

3 Answers3

8

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,269
  • 5
  • 49
  • 72
2

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,152
  • 1
  • 16
  • 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
  • 8,145
  • 4
  • 55
  • 61