Reputation: 21
I want to select all div where such id have a "similar" start and end characters, but has a different middle characters.
`<div id=abc000123>
<div> Text </div>
</div>
<div id=abc111123>
<div> Text </div>
</div>
<div id=abc222123>
<div> Text </div>
</div>`
I have tried:
var elements = document.querySelectorAll("[id$=123]"); console.log(elements);
But I am getting an error:
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '[id$=123]' is not a valid selector.
Upvotes: 1
Views: 440
Reputation: 387
You can use querySelectorAll to hit partial attributes, 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 compare 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.
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/
Upvotes: 1
Reputation: 19485
you are using the css wildcards correctly, only need to use double quotes around the value:
Update: added also selector for beginning [id^="abc"]
var html = `<div id=abc000123>
<div> Text </div>
</div>
<div id=abc111123>
<div> Text </div>
</div>
<div id=abc222123>
<div> Text </div>
</div>`
document.body.innerHTML = html;
var elements = document.querySelectorAll('[id$="123"][id^="abc"]');
console.log(elements);
Upvotes: 3