Home > Enterprise >  how to skip queryselectorall does not exist or null
how to skip queryselectorall does not exist or null

Time:12-18

for (i = 0; i < document.querySelectorAll('span.movie-cast-title').length; i  )
{
  if (document.querySelectorAll('span.gcharacter')[i].innerText, == 'null') {
    continue;
  }
  data.actor.push({
    "@type": "PerformanceRole",
    "actor": {
      "@type": "Person",
      "name": document.querySelectorAll('span.movie-cast-title')[i].innerText,
      "url": document.querySelectorAll('a.movie-cast-url')[i].href,
    }
    "characterName": document.querySelectorAll('span.gcharacter')[i].innerText,
  });
}

how to skip queryselectorall does not exist or null "characterName": document.querySelectorAll('span.gcharacter')[i].innerText

CodePudding user response:

You need to check if the index, that is, i is within the bounds of querySelectorAll:

if(document.querySelectorAll('span.gcharacter').length > i) {
  ...
}

CodePudding user response:

You need to check if the element exists, not the innerText. Because if the element doesn't exist, you can't get its innerText.

if (!document.querySelectorAll('span.gcharacter')[i]) {
    continue;
}

CodePudding user response:

wouldn't it be clearer to use a forEach?

const 
  spCharacters = document.querySelectorAll('span.gcharacter')
, aMovieCast   = document.querySelectorAll('a.movie-cast-url')
  ;
document.querySelectorAll('span.movie-cast-title').forEach( (sp,i) =>
  {
  if (spCharacters[i].innerText !== 'null')
    {
    data.actor.push(
      { '@type' : 'PerformanceRole'
      , 'actor' :
        { '@type' : 'Person'
        , 'name'  : sp.innerText,
        , 'url'   : aMovieCast[i].href,
        }
      , 'characterName': spCharacters[i].innerText
      });
    }
  }
  • Related