Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are JQuery selectors safer than DOM properties?

These 2 expressions do the same thing but which one is safer or even more efficient?

var indexedCellValue = selectedCell.srcElement.parentElement.cells[index].innerText;

var indexedCellValue = $(selectedCell.srcElement).parent('tr').get(0).cells[index].innerText;

(Both a getting a cell's, selectedCell, parent row and indexing into a column on that parent row.)

like image 647
learnerplates Avatar asked Feb 01 '13 12:02

learnerplates


2 Answers

Pure JavaScript is gonna be always faster than jQuery, but with jQuery you ensure that the code is going to work in most of the browsers.

like image 60
davids Avatar answered Sep 24 '22 13:09

davids


With jQuery, you're only selecting elements which has a tr parent. I also think that the pure javascript version would work on firefox 9+, but not older ones.

Under the hood, If you take a look to jQuery's source code, at the definition of parent() (line 5666, as of version 1.9.0):

parent: function( elem ) {
    var parent = elem.parentNode;
    return parent && parent.nodeType !== 11 ? parent : null;
},

You see that it doesn't use parentElement, but parentNode, that is more supported by browsers (primarily not by old versions of Firefox, in fact it wasn't supported by it prior to version 9, if you want to know the differences of the two, see this answer: Difference between DOM parentNode and parentElement).

It also check if the node is a DOCUMENT_FRAGMENT_NODE (frankly I don't know why it does, if anyone knows I'd be interested).

On the 2.0 development branch, which doesn't support old browsers (thanks pimvdb), they switched to parentElement (Reduce traversing module - commit):

parent: function( elem ) {
    return elem.parentElement;
},
like image 32
franzlorenzon Avatar answered Sep 24 '22 13:09

franzlorenzon