最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove image from page if it already exists - Stack Overflow

programmeradmin3浏览0评论

I got multiple images in different divs but sometimes 2 images are exactly the same. How do I remove all except one of those images from the page?

Is this possible with jquery/javascript? Or even css?

Example:

<div id="Content">
 <div class="Media">
  <img src="1.jpg">
 </div>
</div>
<div id="Content">
 <div class="Media">
  <img src="2.jpg">
 </div>
</div>
<div id="Content">
 <div class="Media">
  <img src="1.jpg">
 </div>
</div>
<div id="Content">
 <div class="Media">
  <img src="4.jpg">
 </div>
</div>
<div id="Content">
 <div class="Media">
  <img src="1.jpg">
 </div>
</div>

How do I make it so it only shows one of the divs with:

<img src="1.jpg">

This is the server side code It returns a big json file with all the posts from the twitter page but i didnt think it was possible to filter it so it checks for duplicates first?

       success: function(data){
           twitter = JSON.parse(data);
                for(var key in twitter.statuses){
                    if (typeof twitter.statuses[key].entities.media != "undefined") {

                            if( $.inArray(twitter.statuses[key].entities.media, container) == -1 ) {
                            container.push(twitter.statuses[key]);
                            }
                        }
                }
           },
       error: function(data){
           console.log(data);
       }

I hope someone knows how to solve this problem Thanks!

I got multiple images in different divs but sometimes 2 images are exactly the same. How do I remove all except one of those images from the page?

Is this possible with jquery/javascript? Or even css?

Example:

<div id="Content">
 <div class="Media">
  <img src="1.jpg">
 </div>
</div>
<div id="Content">
 <div class="Media">
  <img src="2.jpg">
 </div>
</div>
<div id="Content">
 <div class="Media">
  <img src="1.jpg">
 </div>
</div>
<div id="Content">
 <div class="Media">
  <img src="4.jpg">
 </div>
</div>
<div id="Content">
 <div class="Media">
  <img src="1.jpg">
 </div>
</div>

How do I make it so it only shows one of the divs with:

<img src="1.jpg">

This is the server side code It returns a big json file with all the posts from the twitter page but i didnt think it was possible to filter it so it checks for duplicates first?

       success: function(data){
           twitter = JSON.parse(data);
                for(var key in twitter.statuses){
                    if (typeof twitter.statuses[key].entities.media != "undefined") {

                            if( $.inArray(twitter.statuses[key].entities.media, container) == -1 ) {
                            container.push(twitter.statuses[key]);
                            }
                        }
                }
           },
       error: function(data){
           console.log(data);
       }

I hope someone knows how to solve this problem Thanks!

Share Improve this question edited Oct 6, 2014 at 11:31 Stefan asked Oct 6, 2014 at 10:57 StefanStefan 1,9057 gold badges25 silver badges38 bronze badges 6
  • Is this html generated dynamically? – David Jones Commented Oct 6, 2014 at 10:59
  • Surely better to do this when you parse the feed? – Alex K. Commented Oct 6, 2014 at 11:01
  • Could you post the code that generates the html? You dont want to create all the html then have to remove some of it. That would be a waste of resources. – David Jones Commented Oct 6, 2014 at 11:03
  • can the image be the same but the source be different? – Enjoyted Commented Oct 6, 2014 at 11:04
  • This needs to be done server side so you can identify if the image is a retweet or not. Unless you can add a attribute to the image to tell the JavaScript that it is a retweet. – David Jones Commented Oct 6, 2014 at 11:10
 |  Show 1 more ment

5 Answers 5

Reset to default 3

You can get all the IMG tags and see if the src is unique. If it isn't, you can remove it. Here is an example:

$(document).ready(function() {
  var img = $("img");
  var used = {};
  img.each(function() {
    var src = $(this).attr('src');
    if(used[src]) $(this).remove();
    used[src]=1;
  });
})

CodePen here: http://codepen.io/cfjedimaster/pen/tDprC

I'm using the filter function from jQuery.

First, I'm selecting all image child elements from the 'Media' class. After that, I'm using the filter function to reduce the set of matched elements to those, which aren't in my array. Then I'm deleting them. (Including the parent node)

I'm not sure whether this is the ideal solution, but you can give it a try.

$(function() {
var $allImages = $( '.Media > img' ),
    tmp,
    allUsedImageSrcs = [];

$allImages.filter( function() {
    tmp = $( this ).attr( 'src' );

    if( $.inArray( tmp, allUsedImageSrcs ) < 0 ) {
        allUsedImageSrcs.push( tmp );
        return false;
    }

    return true;
}).closest( '#Content' ).remove();});

Here's a fiddle of my implementation with jQuery, although you could achieve the same functionality without jQuery.

http://jsfiddle/6jb3hoc9/1/

with javascript you could do it like that (pseudo) idea

$('#content.media img'){
   //fill the array with src 
   //check if array item is same 
   //remove item 
    var array;//array of src tag
    foreach(item in array as value) 
     if(value['src'] == value['src'])
      {
           arr.remove();
          //remove item from dom **
        }

}

How to remove item from DOM http://www.w3schools./js/js_htmldom_nodes.asp

Kind of don't know what you want.

Suppose you want to remove img element with the duplicated src.

// Retrieve all the images
var imgs = document.querySelectorAll(".Media > img");

// To memorize srcs appear before
var srcExisted = [];

for (var i = imgs.length - 1; i >= 0; i--) {

    if (srcExisted.indexOf(imgs[i].src) < 0) {

        // The 1st appearing, memorize
        srcExisted.push(imgs[i].src);

    } else {

        // Already existed, remove
        imgs[i].parentNode.removeChild(imgs[i]);
        imgs[i] = null;

    }
} 

I have write this function for you.

 window.addEventListener("load", function () {
    var images = Array.prototype.slice.call(document.getElementsByTagName('img'));

    if (images.length == 0) {
        return;
    }

    (function handleImages(imgHash) {
        var process = function (image) {
            if (typeof imgHash[image.src] == 'undefined') {
                imgHash[image.src] = true;
            } else {
                image.parentNode.removeChild(image);
            }
        };

        setTimeout(function () {
            process(images.shift());
            if (images.length > 0) {
                setTimeout(function () {
                    handleImages(imgHash);
                }, 0);
            }
        }, 0);
    })({});
}, false);

About your other problem. You must rewrite logic into success to be asynchronous. Check this:

success: function(data){
    var twitter = JSON.parse(data);
    var props = Object.getOwnPropertyNames(twitter.statuses);
    var result = [];
    var dfd = $.Deferred();

    if (props.length == 0) {
        return;
    }

    (function handleProps(propsHash) {
        var process = function (prop) {
            if (typeof twitter.statuses[prop].entities.media != "undefined" && typeof propsHash[twitter.statuses[prop].entities.media] == 'undefined') {
                result.push(twitter.statuses[prop]);
                propsHash[twitter.statuses[prop].entities.media] = true;
            }
        };

        setTimeout(function () {
            process(props.shift());
            if (props.length > 0) {
                setTimeout(function () {
                    handleProps(propsHash);
                }, 0);
            } else {
                dfd.resolve(result);
            }
        }, 0);
    })({});

    dfd.done(function(result) {
        console.log(result);
    });
}

Instead console.log(result); you must call other code that will handle result.

发布评论

评论列表(0)

  1. 暂无评论