'How do I make a button show and hide text when clicked and why does getElement not work?

I have done all the HTML and CSS but the JavaScript part is confusing me. How do I make a button hide or show text when clicked?

There is an error that comes up on the console as well. It says that getElement is not defined. I've also tried using getElementByClassName but the error message still comes up.

The error says Uncaught ReferenceError: getElement is not defined and the same for getElementByClassName

--

In the code:

nav-btn = the button that should to toggle the text

nav-links = the text that should to show up

--

The JavaScript code:

const links = getElement(".nav-links")
const navBtn = getElementByClassName('nav-btn')

links.style.display = 'none';

navBtn.onclick = function () {
    if (links.style.display !== "none") {
        links.style.display = "none"
    } else {
        links.style.display = "block"
    }
}

What do I need to change to make it work?

Also what do I do about the getElement problem?



Solution 1:[1]

Since getElement is not defined, you must be using it as native JS function, which is not available.
If you want to select element with className, you can use querySelector

const links = document.querySelector('.nav-links')

And getElementsByClassName returns an array of nodes, not just single element. So Change it to querySelector for your use case

const navBtn = document.querySelector('.nav-btn')

Solution 2:[2]

As mentioned in the comment below your post getElement isn't a native JS DOM method which is why the error is appearing. Personally I would use querySelector, and add a listener to the button. And then use CSS, and classList, to toggle a show class off and on. It makes for shorter more readable code.

const links = document.querySelector(".nav-links")
const navBtn = document.querySelector('.nav-btn')

navBtn.addEventListener('click', handleClick, false);

function handleClick() {
  links.classList.toggle('show');
}
.nav-links { display: none; }
.show { display: block; }
<div class="nav-links">Nav links</div>
<button class="nav-btn">Toggle the nav!</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kritiz
Solution 2