DEV Community

Nikhil Chandra Roy
Nikhil Chandra Roy

Posted on

When Javascript need to use multiple pages with a selector (Short Tutorial)

Hi Namaskar,
Imagine below the code

let box = document.querySelector('.box')
box.innerHTML = 'I am box'
Enter fullscreen mode Exit fullscreen mode

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'
}
Enter fullscreen mode Exit fullscreen mode

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'
)
Enter fullscreen mode Exit fullscreen mode

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'
)

Enter fullscreen mode Exit fullscreen mode

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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more