0

If I do this in the console:

document.querySelectorAll('.error')

An object of length 3 is returned.

If any of the property values are empty, then I do not want my if statement to run:

After getting frustrated with this (I was using != '') the internet told me to use !== ""

Here is the output for property in the object:

document.querySelectorAll('.error')[0]
""

document.querySelectorAll('.error')[1]
"some string"

document.querySelectorAll('.error')[2]
""

My newness to JS is probably apparent by my question so far. Is the "best" way to check for empty string to use what I have done !==?

<script>

var errorElems = document.querySelectorAll('.error');

for(i=0; i<errorElems.length; i++) {
    if(errorElems[i].textContent !== ""){
        dataLayer.push({
            "event": "errors",
            "eventCategory": "error messages",
            "eventAction": errorElems[i].id,
            "eventLabel": errorElems[i].textContent
            })
        };
    };

This appears to be working. But I'm one person checking in one browser (Chrome) on a desktop machine, if that matters.

What would be the most full proof (yet reasonably straightforwards) means to doing this? Is !== best test?

0

3 Answers 3

3

If its an empty string, !== "" is the way to go. If it can be undefined too (as it very much can happen when selecting DOM elements), then you should make a check like this:

if (typeof string !== 'undefined' && string !== "") 
Sign up to request clarification or add additional context in comments.

Comments

1

empty values are parsed as false, if you just try

if (!errorElems[i].textContent) {
    ... // error handling code here
}

1 Comment

Thank you, this is helpful. Accepting the other answer for no other reason than timing.
1

The Node.textContent property, as per its specification can return a null value, so it would be better to test it with something like this:

var errorElems = document.querySelectorAll('.error'),
    errorElem;

for (i=0; i < errorElems.length; i++) {
    errorElemText = errorElems[i].textContent;
    if (typeof errorElemText === "string" && errorElemText !== "") {
        dataLayer.push({
            "event": "errors",
            "eventCategory": "error messages",
            "eventAction": errorElems[i].id,
            "eventLabel": errorElemText
        });
    }
}

2 Comments

thanks for the tip. So in that case could I not do: if (typeof errorElemText === "string" && errorElemText !== "") in a oner?
Of course. My bad. I pieced it together quickly. I edited my answer accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.