Get all visible text on on page?

Viewed 1317

I want to get all the visible text on a page. Visible text is defined as text that users can find by using Ctrl-F.

This question advises using document.body.innerText but this includes non-visible text in option tags.

Is there a good solution for only getting visible text (Ctrl-F able) on a page?

1 Answers

Does this works for you

  1. Get the body tag

  2. Get all tags inside body

  3. Iterate tags and get element of visible elements

     function isHidden(el) {
         var style = window.getComputedStyle(el);
         return ((style.display === 'none') || (style.visibility === 'hidden'))
     }
    
     // get the body tag
     var body = document.querySelector('body');
    
     // get all tags inside body
     var allTags = body.getElementsByTagName('*');
    
    
     //console.log(allTags);
    
    
     for (var i = 0, max = allTags.length; i < max; i++) {
         if (isHidden(allTags[i])){
             // hidden
         }
         else { 
             console.log(allTags[i].innerText);
         }
     }
    
Related