Does anyone know a solid way to run a [class^='xyz-'] css selector search in vanilla js, without any libraries, on the whole dom without shutting down the browser?
Basically a $('[class^="xyz-"]').length check without the use of jQuery... it only needs to find one occurrence and can break; right after.
Thank you!
edit: should be cross browser & mobile, possibly ie7+
Easy enough with XPath. Faster, too.
var xpathResult = document.evaluate(
'count(//div[starts-with(@class, "xyz-")])',
document,
null,
XPathResult.ANY_TYPE, null);
snippet.log(xpathResult.numberValue);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div></div>
<div class="xyz-foo"></div>
<div class="bar"></div>
<div></div>
A slow option (I believe IE6+):
function getElementsByClassNamePrefix(prefix) {
var els = document.getElementsByTagName("*");
var result = [];
for (var i = 0; i < els.length; i++) {
if (els[i].className.substr(0, prefix.length) == prefix) {
result.push(els[i]);
}
}
return result;
}
snippet.log(getElementsByClassNamePrefix('xyz-').length);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div></div>
<div class="xyz-foo"></div>
<div class="bar"></div>
<div></div>