I'm creating a multipage website that doesn't share the same layout, and by using a single javascript file the console throws an error every time an element is not in the DOM. I'm looking for a solution that avoids me to include every bit of code in an if
statement that check if the element exists.
e.g.
Javascript file
let myelement = document.querySelector('.myelement');
let myelementText = myelement.textContent;
console.log(myelementText);
HTML template #1
<ul>
<li>Element</li>
<li>Element</li>
<li>Element</li>
<li>Element</li>
</ul>
Console output for template #1
Uncaught TypeError: Cannot read property 'textContent' of null
at window.onload ((index):33)
HTML template #2
<ul>
<li>Element</li>
<li>Element</li>
<li>Element</li>
<li class="myelement">Element</li>
</ul>
Console output for template #2
element
Current - and hopefully - avoidable solution
let myelement = document.querySelector('.myelement');
if (typeof (myelement) != 'undefined' && myelement != null) {
let myelementText = myelement.textContent;
console.log(myelementText);
}