Follow this method: By clicking either the radio button or its corresponding label, you can display the ID.
No need to use closest
in this case, but if it matches the selector, closest will return the element itself.
This functionality also works in Bootstrap.
document.querySelector('.btn-group').addEventListener('click', (e) => {
const tgt = e.target;
if (tgt.matches('.btn-check')) console.log(tgt.id)
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea8885859e999e988b9aaadfc4d8c4d9">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<div class="btn-group" role="group" aria-label="Basic radio toggle button group">
<input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off" checked>
<label class="btn btn-outline-primary" for="btnradio1">Radio 1</label>
<input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off">
<label class="btn btn-outline-primary" for="btnradio2">Radio 2</label>
<input type="radio" class="btn-check" name="btnradio" id="btnradio3" autocomplete="off">
<label class="btn btn-outline-primary" for="btnradio3">Radio 3</label>
</div>
If your buttons have child elements, using closest
is necessary.
To display the ID, click on either the button text or the icon.
document.querySelector('.btn-group').addEventListener('click', (e) => {
const tgt = e.target.closest('.btn'); // wouldn't work on the icon without closest
if (tgt) console.log(tgt.id)
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="284a47475c5b5c5a4958681d061a061b">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div class="btn-group" role="group" aria-label="Basic button group">
<button type="button" class="btn btn-outline-primary" id="btn1">Text</button>
<button type="button" class="btn btn-outline-primary" id="btn2" ><i class="fa fa-exclamation-circle" aria-hidden="true"></i></button>
</div>