lundi 14 août 2017

How to validate an HTML element within an 'if-else' statement

I am trying to validate the text content of an element that can only be captured by targeting class and tag names. The text content I am looking for is available by querying 'document.getElementsByClassName('sample')[0].children[1].getElementsByTagName('span')[0].textContent', but in cases where the element or any of its precursors are not on the page, this will throw an error. Is there a better way to check that the text content exists within the conditional, without repeating the checks for each element along the way?

Here is the current implementation:

(function() {
if (!!document.getElementsByClassName('sample')[0].children[1] && 
    !!document.getElementsByClassName('sample')[0].children[1].getElementsByTagName('span')[0] && 
    !!document.getElementsByClassName('sample')[0].children[1].getElementsByTagName('span')[0].textContent) {
    return document.getElementsByClassName('sample')[0].children[1].getElementsByTagName('span')[0].textContent;
} else {
    return 'Text not present.';
}

})();

Aucun commentaire:

Enregistrer un commentaire