1

I want to use document.querySelectorAll to get all the elements having "required" attribute in them. For example:

<input autocomplete="off" name="des" required="">

Please find the code below to retrieve these elements:

  const requiredFields = document.querySelectorAll('[required]');
  console.log('all required fields', requiredFields);

I have tried the code mentioned above, but it returns nothing.

all required fields NodeList []

As per the requirement, required fields should be displayed on page load. All other elements should be hidden. How do I achieve this ? Also, how to get/hide all the elements not having the "required" attribute ?

Thanks

Ashy Ashcsi
  • 1,045
  • 3
  • 16
  • 33

1 Answers1

0

20/01/21 Edit:

you mistake was cominng from require="" check my code below.

as mentioned in the comments require is a boolean attr therefore it doesn't get any value (is rather required or not)

HTML:

<input autocomplete="off" name="des" required value="1">
<input autocomplete="off" name="des" value="2" >
<input autocomplete="off" name="des" required value="3">
<input autocomplete="off" name="des" value="4" >
<input autocomplete="off" name="des" required value="5">
<input autocomplete="off" name="des" required value="6">
<input autocomplete="off" name="des" required value="7">

JS:

const inputs = document.querySelectorAll("[required]")
console.log(inputs)

codepen: https://codepen.io/Elnatan/pen/XWdJrez

Elnatan vazana
  • 352
  • 3
  • 13
  • If you can’t reproduce a problem, ask for clarity in the comments. Answers are for solutions to problems. – Quentin Aug 06 '20 at 11:29
  • I edited my answer and now its working exactly like what you asked for – Elnatan vazana Aug 06 '20 at 11:39
  • Re edit: `required` is a Boolean attribute. It **can’t** have `true` or `false` as values. Even if it could, the code in the question would still select them, so you haven’t done anything that would solve the problem. (I’ll retract the Not An Answer flag though, since it now is an answer, even if it is hopelessly wrong and failing to address the problem the question is focused on). – Quentin Aug 06 '20 at 11:42
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/low-quality-posts/26871679) – cloned Aug 06 '20 at 11:43
  • @Quentin Thank you for the comment, i know the post is closed but it was important for me to fix it. – Elnatan vazana Jan 20 '21 at 11:56