0

How do I optimize the following code, so that the output will assign an attribute to two input fields? I developed the following code, but it doesn't seem to work yet:

  const addAttribute = document.querySelectorAll("#form-field-name, #form-field-escort");
for (let i=0; i<addAttribute.length; i++) {
    addAttribute.setAttribute("onvalid","this.setCustomValidity('Bitte füllen Sie dieses Feld aus.');")
}

I am beginner, so please don't judge me for misunderstanding some code lines. Would really appreciate, if someone could explain to me what I did wrong and help optimize the code to make this working.

leon_505
  • 33
  • 8
  • I've answered your question today but it seems like you've deleted your previous question. `document.querySelectorAll` returns an array, run a loop through items it returns and then use `setAttribute` per that item. – AbsoluteZero Nov 25 '22 at 17:11
  • 1
    `addAttribute[i].setAttribute…` – James Nov 25 '22 at 17:12
  • @AbsoluteZero Yeah and as you can see I already tried to execute your advice and I am stuck. So what's wrong to ask for help here? I am stuck and looking for answers. – leon_505 Nov 25 '22 at 17:15

1 Answers1

0

Here's an example of how to handle document.querySelectorAll with a loop. Apply that to your code.

const els = document.querySelectorAll('.el-1, .el-2');

console.log(els); // NodeList(2) - an array

els.forEach((el) => {
  el.setAttribute('key', 'value');
});
<p class="el-1">First el</p>
<p class="el-2">Second el</p>

I'll even leave the link that I've left for you before here. More examples here.

Please don't remove your questions because you didn't like the answer.

AbsoluteZero
  • 401
  • 7
  • Thanks for making this more clear for me. Really appreciate that! I deleted the questions because stack overflow recommended to delete the question. So don't worry, I liked the answer. I just wanted to post this thread again with a more advanced code snipped. – leon_505 Nov 25 '22 at 17:24