document.querySelector()
would be easier for the purpose of targeting a single element by a selector.
- Target element has an
id
..... document.querySelector("#anyId");
- Target element has a
class
... document.querySelector(".anyClass");
- Target element has no
class
or id
, use the element's tag name ... document.querySelector("div");
If there's more than one target, then the first one will be selected.
Compatible with all browsers even IE8 (limited), see CanIUse and for details see MDN
Btw, IE8 is no longer supported by MicroSoft, see this obituary
var target = document.querySelector('.AnyClass');
var button = document.querySelector('#AnyID');
button.onclick = function() {
target.classList.add('newClass');
}
.AnyClass {
border: 2px solid blue;
height: 100px;
width: 100px;
}
.newClass {
border: 3px dashed red;
background: yellow;
height: 150px;
width: 150px;
}
section {
border: 1px dotted brown;
background: blue;
height: 120px;
width: 120px;
display: inline-block;
}
<div class="AnyClass">TARGET</div>
<button id="AnyID">addClass</button>
<section>SECTION</section>