简体   繁体   中英

Is there a way to get a reference to all the paragraphs or headings in a web page in JavaScript?

I'm writing a simple Greasemonkey script to strip out all the images, headings and paragraphs from a web page (it's because someone wants to use images of several popular websites with the images and text removed in a presentation about branding of websites). I've figured out how to do so with images by using a for loop and the document.images array like this:

var i = 0;
var imglngth = document.images.length;

for(i=0;i<imglngth;i++)
{
    document.images[i].style.display="none";
}

However, I don't believe there's an object representing paragraphs or headers. Any suggestions as to how I could implement this?

If the headers are in <h1> - <h6> tags, you can use the getElementsByTagName method from the DOM API, and a loop to get everything from <h1> to <h6> .

for( i = 1; i<= 6; i++ ) { 
    var tag = 'h' + i;
    var heads = document.getElementsByTagName( tag );
    for ( j = 0; j < heads.length; j++ ) { 
        heads[j].style.display = 'none';
    }
}

If the document does not use header tags, you may have to reverse-engineer their stylesheet and do something with a bit more logic.

Of course, manually traversing the DOM API can be a pain. If you can use something like jQuery, it's a bit easier:

$( ':header' ).each( function() { ... } );

Using jQuery would be very each to get all the <p> elements.

$('p').each(function(){
   // do stuff
});

Here's a link for some info on jQuery and GreaseMonkey

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