简体   繁体   中英

How to use jquery to remove duplicated meta tag?

For some reasons, my page contains two meta tag sections in the header, and they are the same.

I can create a jquery code to remove the duplicated one if this meta tag is only one line; however, my situation is that these meta tags contain 6 lines, like the first part of the following codes showing:

(the second part is the duplicated part I want to remove)

<meta property="fb:app_id" content="123456789">
<meta property="og:site_name" content="MyWebsite">
<meta property="og:url" content="http://ThisIsMyWebsite.com">
<meta property="og:title" content="Duplicated Meta Tag Testing">
<meta property="og:description" content="Test the duplicated meta tags">
<meta property="og:image" content="http://ThisIsMyWebsite.com/show.jpg">

<meta property="fb:app_id" content="123456789">
<meta property="og:site_name" content="MyWebsite">
<meta property="og:url" content="http://ThisIsMyWebsite.com">
<meta property="og:title" content="Duplicated Meta Tag Testing">
<meta property="og:description" content="Test the duplicated meta tags">
<meta property="og:image" content="http://ThisIsMyWebsite.com/show.jpg">

Is there any clear way to find/remove duplicated part?(Keep only one part)

Thank you.

Here's one solution, will keep the first one only:

var found = {};
$('meta').each(function(){
    var $this = $(this);
    if(found[$this.attr('property')]){
         $this.remove();   
    }
    else{
         found[$this.attr('property')] = true;   
    }
});

You can create a for loop and remove all occurrences of each meta property after the first one.

var exists = {};
$('meta').each(function () {
    var meta = $(this);
    var property = meta.attr('property');
    if(!property)
        return;

    if (exists[property]) meta.remove();
    else exists[property] = meta;
});

JSFiddle: https://jsfiddle.net/7hwvyphm/

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