Check if the obj accessed or function called, that used this operator, is undefined
or null
. The expression short circuits and evaluates to undefined
instead of throwing an error.
obj.val?.prop
obj.val?.[expresions]
obj.func?.(args)
- Convention to say: This data will never change after being defined here.
<div id="myDIV">
<p>I am a myDIV.</p>
</div>
const list = document.getElementById('myDiv').classList;
list.add("myStyle")
// or list.toggle("myStyle")
// ...
.myStyle {
color: red;
}
- Add single class:
element.classList.add("myStyle")
- Add multiple classes :
element.classList.add("firstS", "secondS", ...)
- Remove single class:
element.classList.remove("myStyle")
- Remove multiple classes :
element.classList.remove("firstS", "secondS", ...)
element.classList.length
element.classList
element.classList.contains('myStyle')
element.classList.item(1)
element.className = "smt"
const extractedValue = element.getElementById("myDiv").className;
if (element.className == 'old smt') {
element.className = 'new smt';
} else {
element.className = 'old smt';
}
document.getElementById('myBtn').onclick = () => {
myFunc();
}
const myFunc = () => {
document.getElementById('myBtn').classList.toggle('show-smt');
}
Method 2: specify INSIDE HTML file, people tend to not doing this since HTML can't possibly know what's inside JS file
<button onclick="myFunc()">Click me!</button>
<nav class="navbar"></nav>
const navbar = document.getElementById("navbar");
const sticky = navbar.offsetTop;
// add the sticky class to the navbar when reach its scroll position
// remove it when you leave the scroll position
const myFunc = () => {
if (window.pageYOffsetY >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky")
}
}