Let's talk real numbers here.

    http://jsperf.com/xpath-vs-dom


I don't know if I understand the XPath correctly, but it seems to me, that the three examples don't do the same (actually, they do in the given example, but not in general.

document.evaluate("../../h3", button, null, XPathResult.ANY_TYPE, null);

This gets all <h3> elements which are direct children of the button's parent's parent element.

button.parentNode.parentNode.getElementsByTagName("h3")[0];

This gets the first of all <h3> element which are within the button's parent's parent element. So in an example like this

<div class="box">
    <div>
        <h3>Some other title</h3>
    </div>

    <h3>Some title</h3>
    <p class="buttons">
        <button onclick="myfunction(this)">Trigger</button>
    </p>
</div>

These two examples would not match the same element.

$button.parent().parent().find("h3");

Again, this finds all <h3> elements somewhere within the button's parent's parent element. This can be easily fixed by

$button.parent().parent().children("h3").first();

To fix the 'native DOM' example, a loop is needed:

var child = button.parentNode.parentNode.firstChild;
while (child && child.nodeName !== "H3") { child = child.nextSibling; }

In my opinion, when comparing the speed, we need to make sure they compared ways behave the same. So I added a second version of your test: http://jsperf.com/xpath-vs-dom/2 Still shows: Native DOM traversal is much faster than anything else.

Matt

--
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to