Hi Namaskar,
Imagine below the code
let box = document.querySelector('.box')
box.innerHTML = 'I am box'
Typically we follow that away but
if there is no box HTML class else we will see
Uncaught TypeError: Cannot set property 'innerHTML' of null
That is not a good way to use and it will break our javascript code.
Sometimes we are using one javascript file on multiple pages and we have to use the right away so that we can avoid bugs.
we can call the box class selector
like below to avoid bugs.
let box = document.querySelector('.box')
if(box){
box.innerHTML = 'I am box'
}
you see we used if condition to avoid that type of bugs,
also, we can use logical AND condition
box && (
box.innerHTML = 'I am new box'
)
for multiple times to use the box
box && (
box.innerHTML = 'I am new box',
box.setAttribute('style', 'width: 200px; height: 200px;'),
box.style.background = 'red'
)
you notice we use comma instance of semi-colon because of parenthesis.
That is our short tutorial today,
if you need more like these short tutorials don't forget to write your valuable comment.
Thanks all.
Top comments (0)