Get nested button id in header
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>
Solution 1:
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>