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

Time:04-23

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?

CodePudding user response:

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')

CodePudding user response:

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 an listener to the button. And then use CSS, and classList, to toggle a show class off an 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 >Nav links</div>
<button >Toggle the nav!</button>

  • Related