Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to remove jQuery [duplicate]

There is the site : http://youmightnotneedjquery.com/ : and with my AngularJS application, I would really like to remove jQuery. The reason I still need jQuery and I can't just use jQLite that AngularJS comes with is because jQLite does not support selectors based on classes.

The issue with querySelectorAll() is that when I try to run this:

el.querySelectorAll('> .content')

I get this:

SyntaxError: Failed to execute query: '> span' is not a valid selector.

Is there a way to write this selector with just native DOM methods?

like image 443
ryanzec Avatar asked Dec 06 '25 05:12

ryanzec


1 Answers

If you are really forced to use jQuery to find the .content first level childs, use XPath instead, it will do the exact same thing:

var xpathQuery = "./*[@class='content'";
xpathQuery += " or starts-with(@class,'content ')";
xpathQuery += " or contains(@class,' content ')";
xpathQuery += " or substring(@class, string-length(@class)-6)=' content']";
var iterator=document.evaluate(xpathQuery , el, null, XPathResult.ANY_TYPE, null );
var contentNode = iterator.iterateNext();

just be careful using ./ instead of .// is something like using '>' instead of space ' ' in jQuery selectors.

I managed to create a general function for your use:

function findByClassName(el, className, firstLevel) {
    var xpathQuery = firstLevel ? "./" : ".//";
    xpathQuery += "*[@class='" + className + "'";
    xpathQuery += " or starts-with(@class,'" + className + " ')";
    xpathQuery += " or contains(@class,' " + className + " ')";
    xpathQuery += " or substring(@class, string-length(@class)-" + (className.length) + ")=' " + className + "']";

    var iterator = document.evaluate(xpathQuery, el, null, XPathResult.ANY_TYPE, null);
    var nodes = [];
    var node;
    while (node = iterator.iterateNext()) {
        nodes.push(node);
    }
    return nodes;
}

for your use case you should use it like:

var contentNodes = findByClassName(el, 'content', true);

and this is the working jsfiddle DEMO.

like image 166
Mehran Hatami Avatar answered Dec 08 '25 18:12

Mehran Hatami