1

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.

MarkSquall
  • 21
  • 3
  • Does this answer your question? [querySelector, wildcard element match?](https://stackoverflow.com/questions/8714090/queryselector-wildcard-element-match) – chrisbyte Dec 12 '22 at 20:24
  • Also, do not forget to put param values in html tags between quotes ...
    ....
    – bracko Dec 12 '22 at 20:28

2 Answers2

3

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);
IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • Thank you for this @IT goldman. But in my JSP, there are many of them, that starts with some 3 letters and have the same last 3 numbers, some middle number only differs. What if I want to select all divs whose id starts with "abc" and ends with "123", and hide them if and only if the inside div has no value of string Text? Thanks. – MarkSquall Dec 13 '22 at 02:54
  • you can also select like i have modified my answer. then you should probably loop over the `elements` and show/hide them if your condition is met – IT goldman Dec 13 '22 at 07:29
1

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/

Adem kriouane
  • 381
  • 20