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


i trying validate text content of element can captured targeting class , tag names. text content looking available querying 'document.getelementsbyclassname('sample')[0].children[1].getelementsbytagname('span')[0].textcontent', in cases element or of precursors not on page, throw error. there better way check text content exists within conditional, without repeating checks each element along way?

here 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.';     } })(); 

this why queryselector , queryselectorall exist.

(function() {   var el = document.queryselector("sample > :nth-child(2) span")   return el && el.textcontent ? el.textcontent : "text not present."; })(); 

the :nth-child() selector 1-based, that's why uses :nth-child(2) used .children[1].


or @ least, use variables.

(function() {   var el = document.getelementsbyclassname('sample')[0];   el = el && el.children[1] && el.children[1].getelementsbytagname("span")[0];   return el && el.textcontent ? el.textcontent : "text not present."; })(); 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -