Search code examples
javascriptinputgetelementsbytagnamegetelementsbyclassname

how to call on the input in this scenario?


I would like to give a class to each input in this scenario but I don't know how to.

JS:

  document.getElementsByClassName("parent")[0].addEventListener("click",function(){ document.getElementsByClassName("maco")[0].innerHTML="<form><wrap>Name: <input></wrap><wrap>Date Range from <input> to <input></wrap><wrap>Reason:<input></wrap><wrap>Name of Parent:<input></wrap><wrap><button>Enter<button></wrap></form>";
     document.getElementsByClassName("parent")[0].getElementsByTagName("form")[0].classList.add("pl");
     document.getElementsByClassName("parent")[0].getElementsByTagName("form")[0].getElementsByTagName("input")[0].classList.add("first");
     document.getElementsByClassName("parent")[0].getElementsByTagName("form")[0].getElementsByTagName("input")[1].classList.add("second");
     document.getElementsByClassName("parent")[0].getElementsByTagName("form")[0].getElementsByTagName("input")[2].classList.add("third");
     document.getElementsByClassName("parent")[0].getElementsByTagName("form")[0].getElementsByTagName("input")[3].classList.add("fourth");
     document.getElementsByClassName("parent")[0].getElementsByTagName("form")[0].getElementsByTagName("input")[4].classList.add("fifth"); });

i did the above but the browser kept saying Uncaught TypeError: Cannot read property 'getElementsByTagName' of undefined

Is there a way to give each input in the quote in innerHTML="..." a class?


Solution

  • Since you didn't post your HTML structure it's hard to be sure this will work, but assuimg your tree is like this:

    <div class="parent">
       <form>
          <input>
          <input>
          <input>
       </form>
    </div>
    

    Here's how I would do this.

    const numericalWords = [
      "first",
      "second",
      "third"
    ]
    
    
    document.querySelectorAll('.parent form input').forEach((input, i) => {
      input.classList.add(numericalWords[i])
     })
    .first {
        background: yellow;
     }
     
     .second {
        background: blue;
     }
     
    .third {
        background: green;
     }
    <div class="parent">
    <form>
      <input>
      <input>
      <input>
    </form>
    </div>