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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With