0

I want to add class to this li with class .nav-link. I am using JS for it, but I don't know why this code is not functioning. P.s: I am new to JavaScript

<script>
        const navLink = document.querySelector('.nav-link');

        navLink.addEventListener("click", reveal);
        
        function reveal(ev) {
            ev.classList.add("open");
        }

</script>
3
  • How do you check if the class list was added or not? Do expect a style change on click or something like that? Commented Dec 30, 2020 at 16:40
  • Can you provide a more complete snippet including the HTML? Also, assuming you are using a modern browser to test this out, have you used the debug console to see if there are any errors? For instance, if using Chrome on Windows or Linux, you can press Ctrl+Shift+I (or select More Tools > Developer Tools from the application menu) to open the developer tools. You should be able to see any errors in the Console tab. Commented Dec 30, 2020 at 16:56
  • Yes, I checked for errors in console, but there was none. I had put different style on the class which was to be added to check the effect. Commented Jan 1, 2021 at 16:21

1 Answer 1

1

You have to use ev.target to get that element.

<script>
        const navLink = document.querySelector('.nav-link');

        navLink.addEventListener("click", reveal);
        
        function reveal(ev) {
            ev.target.classList.add("open");  // <----------- Fix this line
        }

</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.