How to select multiple identifiers on a poorly designed web page?

I support a sophisticated web application.

I have a large number of divs that have the same ID .

I know that this is completely wrong, and essentially document.getElementById() with this id will produce only one match for me.

However, I can pull out the element I'm looking for using jQuery (we are on 1.6.2), for example: $('#bad_id[nonstandard_attr_name=somethingSpecific]')

Not quite ready to say that this is a "solution."

I worry about whether it is reliable or not. Is jQuery really collecting a search for all elements matching an ID using a DOM walk? This is probably the only way to get all of them.

First, it filters the elements by a different attribute, and then filters it by identifier? It would also provide the desired behavior, but it would be nice to know the order in which he does it.

+4
source share
4 answers

If you need to select multiple elements with the same identifier, you can simply use the attribute selector:

 $( "[id='myid']" ) 

The attribute selector does not consider an attribute key for any semantics, such as unique identifiers or such.

http://jsfiddle.net/ZWm3G/

+8
source

I cannot tell you what jQuery or other movements will do (it is doubtful that it will always work), but you can try the following:

 document.filter = function(attr, val, r) { r = r || document.getElementsByTagName("*"); var s = []; for(var i = 0; i < r.length; i++) { if(r[i].getAttribute(attr) == val) { s.push(r[i]); } } return s; }; var s = document.filter("nonstandard_attr_name", "somethingSpecific", document.filter("id", "bad_id")); console.log(s); 

http://jsfiddle.net/KGPFf/1/

0
source

Use a selector that will cause something other than the used getElementById() to produce consistent results, but make sure you check it with IE8 since IE8 does not use document.querySelectorAll() .

Using methods such as .find .children and .filter should also produce consistent results regardless of the unique identifier.

Example: http://jsfiddle.net/gb3Mz/

0
source

Well, as can be seen from the comments, I assumed why he would look for any element. yes getElementById returns the first element and then stops the search, but the same is not suitable for jQuery. It returns all elements with this "bad" identifier.

As you can see in this fiddle ,

Thus, it selects all the elements, which means that jQuery does not stop at the first element, but continues to search the entire drawing, therefore IMO, you can use jQuery to select several elements with a common identifier. There should be no problem.

0
source

Source: https://habr.com/ru/post/1495582/


All Articles