To simplify the process, it's best to pass the entire element instead of just the ID to the function. This way, you can directly access the element's ID without needing to query the DOM again:
function clickTab(el) {
el.className = " active";
// Retrieve the ID
var id = el.id;
console.log(id);
}
.active {
background-color:red;
}
<div id="communitytab" onClick="clickTab(this)">Interesting community content</div>
It's important to avoid using inline JS. Instead, utilize Element.addEventListener
which will pass the DOM node as this
. Additionally, make use of classList
instead of className
as it is widely supported (~98% of browser traffic), allowing you to easily manipulate classes with methods like el.classList.add('active')
:
function clickTab() {
var el = this;
el.classList.add('active');
// Retrieve the ID
var id = el.id;
console.log(id);
}
document.getElementById('communitytab').addEventListener('click', clickTab);
.active {
background-color:red;
}
<div id="communitytab">Interesting community content</div>