I'm trying to reference my button (which is nested inside my header/nav), to make an event onclick, but I can't seem to get it to work.
Tried nesting getElementByName with getElementById tried some querySelector and querySelectorAll
Tried:
var x = document.getElementsByClassName('hdr');
var y= x.querySelector('hdrBtns');
z = y.getElementById('singUp');
Tried:
const brt = document.querySelectorAll('.hdr .hdrBtns');
const dac = brt.getElementById('signUp');
Code Underneath:
<body>
<header class="hdr">
<div class="hLogo">
<h1>
Test
</h1>
</div>
<nav class="hdrBtns">
<button id="singUp">Sign Up</button>
<button id="singIN">Sign In</button>
</nav>
</header>
<script src="./script.js"></script>
</body>
The NodeList returned by Element#querySelectorAll() or getElementsByClassName() does not have Methods other Elements have, like getElementById() or querySelector().
Assuming you only have one Element with your particular ID, like you should have, just selecting the element by this will work:
let btn = document.querySelector("#singUp")
btn.addEventListener("click", () => alert("test"))
<header class="hdr">
<div class="hLogo">
<h1>
Test
</h1>
</div>
<nav class="hdrBtns">
<button id="singUp">Sign Up</button>
<button id="singIN">Sign In</button>
</nav>
</header>
A lot ways to do that. But If you looking for a element which already has an id then would be the best to use getElementByID() function. Otherwise you can use querySelector in many different ways.
const btns = document.querySelectorAll('.hdr nav button');
let id1 = btns[0].getAttribute('id');
let id2 = btns[1].getAttribute('id');
console.log('v1',id1, id2)
const b1 = document.querySelector('.hdr nav button:first-child');
const b2 = document.querySelector('.hdr nav button:last-child');
console.log('v2', b1.getAttribute('id'), b2.getAttribute('id'));
const b3 = document.getElementById('singUp');
const b4 = document.querySelector('#singIN');
console.log('v3', b3.getAttribute('id'), b4.getAttribute('id'));
<body>
<header class="hdr">
<div class="hLogo">
<h1>
Test
</h1>
</div>
<nav class="hdrBtns">
<button id="singUp">Sign Up</button>
<button id="singIN">Sign In</button>
</nav>
</header>
<script src="./script.js"></script>
</body>
You simply have to use this code:
var signUp = document.getElementById('signUp');
signUp.addEventListener('click', () => {
// Do something...
});