开发者

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

开发者 https://www.devze.com 2022-12-26 15:03 出处:网络
I\'m writing a simple Greasemonkey script to str开发者_开发技巧ip out all the images, headings and paragraphs from a web page (it\'s because someone wants to use images of several popular websites wit

I'm writing a simple Greasemonkey script to str开发者_开发技巧ip 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

0

精彩评论

暂无评论...
验证码 换一张
取 消