jeudi 11 octobre 2018

Why does my if statement work with an else if, but not an OR operator

I wrote a small piece of JS in the console, to loop through recommended connections on LinkedIn and if the text contains a certain word, ignore that card, otherwise click the 'X' close button.

Initially I wrote it like this:

const list = document.querySelector('.mn-pymk-list__cards');
const cards = list.querySelectorAll('.mn-pymk-list__card');

cards.forEach( (card, i) => {

  setTimeout( ()=>{
    let text = card.querySelector('.member-insights__count');

    if( !text.textContent.includes('Sharon') || text === null ) {
        card.querySelector('.pymk-card__close-btn').click();
       } else {
        card.style.background = 'green';
       }
  }, i * 1000 )

});

However, when it ran, it would sometimes error (whilst continuing to iterate) with 'Could not read textContent of null'.

However, when I wrote the code like this:

const list = document.querySelector('.mn-pymk-list__cards');
const cards = list.querySelectorAll('.mn-pymk-list__card');

cards.forEach( (card, i) => {

  setTimeout( ()=>{
    let text = card.querySelector('.member-insights__count');

    if( text === null ) {
        card.querySelector('.pymk-card__close-btn').click();
    } else if (!text.textContent.includes('Sharon')) {
        card.querySelector('.pymk-card__close-btn').click();
    } else {
        card.style.background = 'green';
    }
  }, i * 1000 )

});

It runs absolutely fine and does what I want it to.

QUESTION: I can't understand why the first option doesn't work, as it seems more concise and theoretically should do the same thing?

I suspect it has something to do with the fact that on LinkedIn, some of the suggested contacts don't have a class of '.member-insights__count' and instead have '.member-insights__info'.

But, that should still make text resolve to null, right?

Any insight would be great!

Aucun commentaire:

Enregistrer un commentaire