Reputation: 37
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.
let myelement = document.querySelector('.myelement');
let myelementText = myelement.textContent;
console.log(myelementText);
<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)
<ul>
<li>Element</li>
<li>Element</li>
<li>Element</li>
<li class="myelement">Element</li>
</ul>
Console output for template #2
element
let myelement = document.querySelector('.myelement');
if (typeof (myelement) != 'undefined' && myelement != null) {
let myelementText = myelement.textContent;
console.log(myelementText);
}
Upvotes: 0
Views: 326
Reputation: 6742
There is no way around to check if the element exists. You can remove the typeof undefined
check, a check for != null
should be enough.
Where you implement this check is up to you, you can use something like this to not select myelement in the first case.
if (document.querySelector('.myelement') !== null) {
alert('The element "myelement" exists in the page.');
} else {
alert('The element "myelement" does not exists in the page.');
}
let myelement = document.querySelector('.myelement');
if (myelement != null) {
let myelementText = myelement.textContent;
console.log(myelementText);
}
<ul>
<li>Element</li>
<li>Element</li>
<li>Element</li>
<li>Element</li>
</ul>
Upvotes: 1