简体   繁体   中英

remove image element based on source

How can I use vanilla javascript + regEx to remove image elements, based on their source?

I am reading a RSS feed with a web app. I want to remove certain image elements if their source contains the word "comments".

It would be ideal to edit the rss feed before it's rendered onto the page (just pulled from the http request, and still in a 'string').

update: Thanks for the replies. At the very bottom of each article, they are including a link to comments... which is what I want to remove. Here is the code at the very end of each article:

<a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ADDRESS/FEED"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/[ADDRESS]/[FEED]" /></a>

also, the [feed] value changes per article. So would it be better to check for the word 'comments' or check if the source starts with x?

var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
    var img = images[i];
    if (img.src.indexOf('comments') > 0) {
       var link = img.parentNode;
       link.parentNode.removeChild(link);
    }
}
  • line 1: get a list of all images elements on the page
  • line 2: iterate over the list, remove those who's src has the word 'comments'. This is done by calling the indexOf method of any string object. Detailed here

You may try this

var imgs=document.images;
for(i=0;i<imgs.length;i++)
    if(imgs[i].src.test('comments'))
        imgs[i].parentNode.parentNode.removeChild(imgs[i].parentNode);​

DEMO .

Thanks for the replies. lins05 suggested some code that i've adjusted slightly. Note: instead of removing the element or it's parent, the following code simply hides the element.

    var images = document.getElementsByTagName('img');
    for (var i = 0; i < images.length; i++) {
        var img = images[i];
        if (img.src.indexOf('comments') > 0) {
            img.style.display = "none";
        }
    }

The rss feed's list of articles are stored in a model on the page. It would be more ideal to chop the comments out of the model.. however the current approach of 'hiding the element every time the article is on the page' works fine :)

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