Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the ID of every element where required = true

I have a list of many select or input and i want to get the id of each of them who have "required=true"
here’s the beginning of my code

function getRequiredFieldsId(contenerId)
{
    // Detection of all select fields
    let objFields = document.getElementById(contenerId).getElementsByTagName('select');
    let q=1;
}

I maybe need to do a forEach but i don’t really know how to do it properly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can use .querySelectorAll("[required]") to get all required element

then if you want only id you can use map

[...requiredElements].map(element => element.id);
function getRequiredFieldsId(contenerId)
{
    let requiredElements = document.getElementById(contenerId).querySelectorAll("[required]");
    requiredElementsId = [...requiredElements].map(element => element.id);
    console.log(requiredElementsId);
}

getRequiredFieldsId('container1');
<div id="container1">
  <input id="test1"/>
  <input id="test2" required/>
  <input id="test3" required/>
</div>

<div id="container2">
  <input id="test1" required/>
  <input id="test2"/>
  <input id="test3"/>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading