So this is an interesting question, and it is very impossible to do it effectively. But I'm interested in finding an effective way to request all html elements in a document that have a specific value set for any attribute. So, for example, instead:
document.querySelectorAll('[attrName]');
I am looking for the equivalent of the following pseudocode:
document.querySelectorAll('[*=specificValue]');
Thus, essentially the result will be all elements that have any attribute whose value matches "specificValue". I know that there are rough ways to do this, for example:
var all = document.querySelectorAll('*'); var matches = []; var attrs; for (var i = 0; i < all.length; i += 1) { attrs = Array.prototype.slice.call(all[i].attributes); for (var j = 0; j < attrs.length; j += 1) { if (attrs[j].value === 'specificValue') { matches.push(all[i]); break; } } }
However, I would really like to avoid parsing every html element like this. Any ideas?
Edit:
Thanks for all the help. Before too many people give alternative suggestions, I must explain why this is necessary. In principle, this is an experiment. The idea was that I could create live bindings to objects in real time, like what you get in Ember.js, but instead of collecting templates, you can just use regular html attributes and have a syntax marker in value, you need to create a binding. For example: <a href="{{linkLocation}}"></a> . I thought it might be interesting if there was an effective way to select the appropriate elements on the fly. It is clear that I know that the cycle should happen somewhere. However, if the browser runs its own iteration, I would prefer my own JavaScript loop. I was just not sure if there was any “secret” selector syntax that I did not know about, or anyone could think of other interesting tricks.
source share