How can I select nodes that begin with a "x-"
tag name, here is an hierarchy DOM tree example:
<div>
<x-tab>
<div></div>
<div>
<x-map></x-map>
</div>
</x-tab>
</div>
<x-footer></x-footer>
jQuery does not allow me to query $('x-*')
, is there any way that I could achieve this?
There is no native way to do this, it has worst performance, so, just do it yourself.
Example:
Full example:
http://jsfiddle.net/6b8YY/3/
Notes: (Updated, see comments)
If you are wondering why I use this way for checking tag name, see:
JavaScript: case-insensitive search
and see comments as well.
Also, if you are wondering about the
find
method instead of adding to selector, since selectors are matched from right not from left, it may be better to separate the selector. I could also do this:$("*", $("div"))
. Preferably though instead of justdiv
add an ID or something to it so that parent match is quick.In the comments you'll find a proof that it's not faster. This applies to very simple documents though I believe, where the cost of creating a jQuery object is higher than the cost of searching all DOM elements. In realistic page sizes though this will not be the case.
Update:
I also really like Teifi's answer. You can do it in one place and then reuse it everywhere. For example, let me mix my way with his:
It's the same performance hit, but more convenient API.
Although this does not answer the question directly it could provide a solution, by "defining" the tags in the selector you can get all of that type?
Try this
Basically jQuery selector works like CSS selector. Read jQuery selector API here.
Demo Fiddle
The below is just working fine. Though I am not sure about performance as I am using regex.
Working fiddle
PS: In above sample, I am considering
body
tag as parent element.UPDATE :
After checking Mohamed Meligy's post, It seems regex is faster than string manipulation in this condition. and It could become more faster (or same) if we use
find
. Something like this:jsperf test
UPDATE 2:
If you want to search in document then you can do the below which is fastest:
jsperf test
Workaround: if you want this thing more than once, it might be a lot more efficient to add a class based on the tag - which you only do once at the beginning, and then you filter for the tag the trivial way.
What I mean is,
After this, you can do a $("[class^='tag--x-']") or the same thing with querySelectorAll and it will be reasonably fast.