Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
194
rated 0 times [  199] [ 5]  / answers: 1 / hits: 29079  / 10 Years ago, wed, october 29, 2014, 12:00:00

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 ?


More From » html

 Answers
36

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/


[#68982] Sunday, October 26, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brynnleslis

Total Points: 425
Total Questions: 100
Total Answers: 115

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;