I'm struggling here with some javascript code I need. I have an html document with more than 300 inputs (type text). All inputs have an id, some inputs also have a name (similar to the id). I want to loop through all input tags that have an ID but do not have a name and for each one add a name attribute identical to the ID.
I think it's simple and I know how to find or loop through elements with specific ID but there is something I'm missing and cant figure it out.
You can use querySelectorAll with the attribute selector [attr], loop through and check if it's got a name, if not copy the ID to the name.
eg.
for (const el of document.querySelectorAll('input[id]')) {
if (!el.getAttribute('name')) {
el.setAttribute('name', el.getAttribute('id'));
}
}
console.log(document.querySelector('form').innerHTML);
<form>
<input id="bob"/>
<input id="john"/>
<input name="gotname"/>
</form>