'How should I add an id attribute using Javascript?
I attempted to create a button id when I clicked on using Javascript. Here's something from my code.
<div class="DivButton" style="" onclick="divClick()"></div>
function divClick()
{
$(this).attr("id") =="Active";
}
Here is my JavaScript function but it doesn't work as expected.
Solution 1:[1]
You can pass this
into divClick
function.
function divClick(e){
e.id = "Active";
console.log(e);
}
<div class="DivButton" style="" onclick="divClick(this)">a</div>
<div class="DivButton" style="" onclick="divClick(this)">b</div>
<div class="DivButton" style="" onclick="divClick(this)">c</div>
Solution 2:[2]
let btn = document.querySelector('DivButton');
btn.setAttribute("id","Active");
Solution 3:[3]
It is generally not a good idea to use inline event handlers.
If you only add an id to elements, you'll end up with duplicate id's, which is not allowed in html. Better use an .active css-class.
The snippet uses event delegation.
document.addEventListener("click", handle);
function handle(evt) {
if (evt.target.classList.contains("DivButton")) {
document.querySelectorAll(".DivButton")
.forEach( bttn => bttn.classList.remove("active") );
return evt.target.classList.add("active");
}
}
.DivButton {
cursor: pointer;
width: 125px;l
height: 2rem;
line-height: 2rem;
text-align: center;
border: 1px solid #999;
margin: 0.3rem;
}
.active {
color: red;
background-color: #FFFFC0;
}
<div class="DivButton active">a</div>
<div class="DivButton">b</div>
<div class="DivButton">c</div>
Solution 4:[4]
You should probably check if the id
active exists and remove it if it does so it can be added to the new button.
function divClick(e,idToAdd){
if(document.querySelector('#active')){
document.querySelector('#active').removeAttribute('id');
}
e.id = 'active';
}
.DivButton {
display: inline-block;
margin: 1rem;
padding: .5rem 3rem;
background: #000;
color: #fff;
cursor: pointer;
}
#active {
background: red;
}
<div class="DivButton" style="" onclick="divClick(this)">a</div>
<div class="DivButton" style="" onclick="divClick(this)">b</div>
<div class="DivButton" style="" onclick="divClick(this)">c</div>
Solution 5:[5]
Try this html code
<div class="DivButton" style="" onclick="divClick(this)">Button1</div>
<div class="DivButton" style="" onclick="divClick(this)">Button2</div>
<div class="DivButton" style="" onclick="divClick(this)">Button3</div>
Javascript code id should be unique
<script>
function divClick(e){
e.id = Math.floor(Math.random() * 10);
}
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sudhir Ojha |
Solution 2 | RobC |
Solution 3 | KooiInc |
Solution 4 | prettyInPink |
Solution 5 |