0

I'm having issues with my javascript in that it doesnt seem to be able to find the elements necessary. The second function with the onload works fine and wont let the form submit without certain fields filled out but the first function seems stuck. Is it not waiting for the DOM to load correctly? Also why cant I put everything under the first function since it waits for the DOM as expected and can find the elements necessary? I'm only using vanilla Javascript. No Jquery yet.

    // my-script.js
document.addEventListener("DOMContentLoaded", function(event) {
    // this function runs when the DOM is ready, i.e. when the document has been parsed
    document.getElementsByClassName(".required").style.backgroundColor="blue";
});

window.onload=function(){

  document.getElementById("mainForm").onsubmit = function(e){
    var pass = document.querySelector("form textarea").value;
    var inputField = document.querySelector(".rectangle > input");
    if (inputField.type=="checkbox"){
      if (!inputField.checked){
        e.preventDefault();
        alert("Check the license box")
      }
    }
    if(pass=="" || pass == null){
      e.preventDefault();
      alert("Enter a description");
    }
  }
}
Loyal_Burrito
  • 125
  • 2
  • 14
  • 2
    `document.getElementsByClassName("required")[0].style.backgroundColor="blue";`-------`getElementsByClassName()` returns collection.....use index. – Mamun Oct 23 '18 at 08:25
  • 1
    Remove the `.` in ('required`) - so, document.getElementsByClassName("required") – sol Oct 23 '18 at 08:25
  • Also make sure `addEventListener` is working, old IE versions dont support it. – kiranvj Oct 23 '18 at 08:30

1 Answers1

0

When giving a class name to getElementsByClassName() you don't need to use the ..
So the correct line would be:

document.getElementsByClassName("required").style.backgroundColor="blue";

If you are using the '.required' class multiple times you could do something like the following:

var x = document.getElementsByClassName("required");
x[0].style.backgroundColor="blue";

That will style the first element given the required class.

If you want to change the background colour of all the elements that have the required class you can do this by the following:

var x = document.getElementsByClassName("required");

for (i = 0; i < x.length; i++) {
    x[i].style.backgroundColor = "blue";
} 
JesseH
  • 53
  • 8
  • `getElementsByClassNames` returns **always** an array, even if only one elements is assigned to this class. – Amessihel Oct 23 '18 at 09:04
  • Good to know. Never had any problems with single class. – JesseH Oct 23 '18 at 10:55
  • It's actually an HTMLCollection. I just made a few tests with Firefox 60.x.y ESR in the log console... I get an error when I try `getElementsByClassName.style.backgroundColor`. What browser do you use? – Amessihel Oct 23 '18 at 11:04