Search code examples
javascripthtmlselectors-api

How to handle 'queryselected' element that are not in the DOM


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);
}

Solution

  • 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>