简体   繁体   中英

How do you set only the content of the grand-grand-…-children of a div to ''?

You have a html like this

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">    
<html>         
  <head>           
    <meta http-equiv="content-type" content="text/html; charset=utf-8">           
    <title>        
    </title>         
  </head>         
  <body>        
    <div>          
      <div>          
        How are you?           
      </div>          
      <div>            
        <div>              
          <div>              
            <p>                
              Hello               
            </p>              
          </div>            
        </div>          
      </div>        
    </div>        
    <div>        
    </div>         
  </body>    
</html>

How do you set only the content of the "nestedmost" div to '' in a userscript that works with most pages? In this context, How are you stays but <p>Hello</p> is removed.

Context: the goal is to automatically filter forum posts(ie the smallest unit) or articles that contain certain keywords but not the whole page because somewhere nested there are keywords.

It's not entirely clear to me what you are looking for, but here's a function that function that finds the most deep div in the document body tree:

function find_deepest_div() {
    var deepest_div;
    var deepest_div_depth = -1;
    function search(current, depth) {
        if (current.tagName === "DIV" && depth > deepest_div_depth) {
            deepest_div = current;
            deepest_div_depth = depth;
        }
        for (var i = 0, len = current.children.length; i < len; i++)
            search(current.children[i], depth + 1);
    }
    search(document.body, 0);
    return deepest_div;
}

You can use it to delete the contents of the deepest div like so:

var deepest_div = find_deepest_div();
if (deepest_div) deepest_div.innerHTML = "";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM