-2

I've looked at various websites but non have helped. To me everything seems to be correct, but I can't get the

document.getElementByClassName("first").style.display="none"; 

to work no matter how many times I tried, I kept getting the same error message on JS;

ERROR:'document' is not defined.[no-undef]

Tried defining the 'document' part and didn't help. Maybe, I was doing the connection between external folders incorrect I tried that and nothing changed

HTML:

<html>
 <head>
       <script src="JS.js"></script>
 </head>
 <body>
 <div class="first">
    <p>Hello and welcome to my first page<br>
    in this page I will test out new think<br>
    and see what works and what doesn't<br>
    </p>
</div>
<button type="button" onclick="myFunction">Click me</button>
</body>
</html>

JS:

function myFunction(){
    document.getElementsByClassName("first").style.display="none";

The button is suppose to clear all he style's from "first".I've changed many outcomes and have nothing happen to the code just the same error repeating its-self over and over again.

nathancy
  • 42,661
  • 14
  • 115
  • 137

2 Answers2

6

document.getElementByClassName() returns an array of elements, so you'll need the index of the element you want to target.

You should call the function by myFunction() and add [0] to getElementsByClassName to get specific element.

function myFunction() {
    document.getElementsByClassName("first")[0].style.display="none";
}
<html>
 <head>
       <script src="JS.js"></script>
 </head>
 <body>
 <div class="first">
    <p>Hello and welcome to my first page<br>
    in this page I will test out new think<br>
    and see what works and what doesn't<br>
    </p>
</div>
<button type="button" onclick="myFunction()">Click me</button>
</body>
</html>
Aditya Thakur
  • 2,562
  • 2
  • 10
  • 21
Chaska
  • 3,165
  • 1
  • 11
  • 17
0

It seams that the error you are recieving comes from a linter, but has nothing to do with your code not working. To fix your linter issue, you might want to have a look at this post. For errors that are produced at runtime, you should have a look at your browser console (In most cases opened with F12).

In regards to your main issue, there are two things to fix:

1)
Your inline onclick handler should be called like so:

<button type="button" onclick="myFunction()">Click me</button>

2)
Instead of using document.getElementsByClassName() - which returns an array - I recommend you to use document.querySelector() instead, as it returns just the first element it found and is much easier to use, if you are already familiar with css selectors. For more information an the querySelector-function have a look at this page.

So, in your code it should look like this:

function myFunction() {
  document.querySelector(".first").style.display="none";
}
Cr45hCode
  • 52
  • 3