I have, the div
's where id looks like this_div_id_NUMBER
, all div
's has the different NUMBER
part. How I find all div
's just using this_div_id
part of id ?

- 2,507
- 6
- 38
- 82
-
1Can you post your div, we can't imagine that much. – Nad Oct 29 '14 at 08:04
-
@User089247 It's not multiple identical IDs, it's several similar IDs, but they are all unique. – Scimonster Oct 29 '14 at 08:09
-
1@NadeemKhan Yes we can, the problem is well enough described. HTML code isn't required for every single thing. – Scimonster Oct 29 '14 at 08:10
-
@Scimonster: Ohk, i got it.Anyways sorry. – Nad Oct 29 '14 at 08:16
6 Answers
you can use querySelectorAll to hit partial attribs, including ID:
document.querySelectorAll("[id^='this_div_id']")
the ^ next to the equal sign indicates "starts with", you can use * instead, but it's prone to false-positives.
you also want to make sure to use quotes (or apos) around the comapare value in attrib selectors for maximum compatibility on querySelectorAll; in jQuery and evergreen browsers it doesn't matter, but in vanilla for old browsers it does matter.
EDIT: late breaking requirement needs a more specific selector:
document.querySelectorAll("[id^='this_div_id']:not([id$='_test_field'])");
the not() segment prevents anything ending with "_test_field" from matching.
proof of concept / demo: http://pagedemos.com/partialmatch/

- 16,370
- 5
- 40
- 36
querySelectorAll
querySelectorAll takes CSS selectors and returns a HTMLNodeList (a kind of array) of all the elements matching that css selector.
The css selector ^
(starts with) can be used for your purpose. Learn more about it in this article.
For your case, it would be document.querySelectorAll("[id^='this_div_id']");
Note that querySelectorAll
doesn't return a live node list. That means, any changes to the dom would not be updated live in the return value of the function.
Another method would to assign all your elements a specific class and then you can use getElementsByClassName
(which is much faster than querySelector).
var divs = document.getElementsByClassName("divClass");

- 1
- 1

- 6,961
- 3
- 26
- 34
Try this selector:
[id^="this_div_id_"]
Pure JavaScript: (reference)
document.querySelectorAll('[id^="this_div_id_"]')
jQuery: (reference)
$('[id^="this_div_id_"]')
CSS: (reference)
[id^="this_div_id_"] {
/* do your stuff */
}
Why is this working?
With the [] in the selector, you can select attributes. Use '=' to match exactly the value or use the '^=' to check if the value starts with. Read more about this here.

- 2,545
- 17
- 23
It is better to use classes. But there is one solution that you need (assuming you use jQuery):
$("*[id^='this_div_id']")

- 111
- 1