Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of jQuery's .before() function in Javascript?

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

like image 237
Akos Avatar asked Mar 14 '14 13:03

Akos


2 Answers

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 );
        }
    });
}
like image 168
Karl-André Gagnon Avatar answered Sep 20 '22 05:09

Karl-André Gagnon


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.

like image 22
Arjit Avatar answered Sep 21 '22 05:09

Arjit