-2

I am working on a task where I have to manipulate some data in input fields that have similar named and ID'd elements.

let's just say things like ID_1 ID_2 or SCH_name SCH_start SCH_end. If I wanted to for example hide all those input fields based on their ID prefix is there something like a "contains" that would do that?

Jack Parker
  • 547
  • 2
  • 9
  • 32
  • 1
    you can use queryselector – apple apple Jun 24 '20 at 13:05
  • use classes and queryselector – pretzelhammer Jun 24 '20 at 13:07
  • [Locating DOM elements using selectors](https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors) with making use of attribute selectors – Peter Seliger Jun 24 '20 at 13:08
  • @MarkBaijens There are no duplicate IDs in this question. – Sebastian Simon Jun 24 '20 at 13:10
  • `var inputs=document.getElementsByTagName("input");` `for(var input of inputs) if(input.id.includes("SCH") && (input.id.indexOf("SCH")==0)) input.style.display="none";`. This checks that "SCH" is in the id AND that it's at the beginning of it. I'm sure there are easier ways to check that. To undo the hiding: `input.style.display="";` – iAmOren Jun 24 '20 at 13:35

2 Answers2

2

Note: Maybe you should add classes to your element.


You can use querySelectorAll

for(let elem of document.querySelectorAll("[id^=d]")){
  console.log(elem.id)
}
<div id="d1">1</div>
<div id="d2">2</div>
<div id="d3">3</div>
<div id="w1">1</div>
<div id="w2">2</div>
<div id="w3">3</div>
apple apple
  • 10,292
  • 2
  • 16
  • 36
1

What you want is probably an Attribute selector (MDN)

[attr^=value]

Represents elements with an attribute name of attr whose value is prefixed (preceded) by value.

So yours would be:

[id^="ID_"] {
}
Ross Mackay
  • 940
  • 4
  • 10