Caisahr
Caisahr

Reputation: 47

Check for duplicate links in the DOM

I'm trying to detect wether my site has articles with the same a href link to prevent duplicate articles showing right below each other. The site is built in Wordpress and I've made the following query to show the articles:

$popular = new WP_Query(
    array(
        'posts_per_page'=>4,
        'cat'=>[-48],  // don't display category with this ID in the array
        'meta_key'=>'popular_posts',
        'orderby'=>'meta_value_num',
        'order'=>'DESC',
        'date_query' => array(
            array(
                'after' => array(
                    'year'  => date('Y', $date ),
                    'month' => date('m', $date ),
                    'day'   => date('d', $date ),
                ),
            )
        )
    )
);

This is put in a while loop. Another one like this is right below it in a different .php file and they're both being loaded in via a parent file with the get_template_part function.

Now I've written the following to log the links that I need, with this:

jQuery(document).ready(function($){
    var links = document.querySelectorAll('.top-post .post-title a');
    for(var i = 0; i < links.length; i++){
        console.log(links[i].href);
    };

    var links2 = document.querySelectorAll('.tiles .post-title a');
    for(var i = 0; i < links2.length; i++){
        console.log(links2[i].href);
    };
});

This of course doesn't help me to write an if statement, because they're both in their individual for loop and I can't reach them. I've also tried to make a var outside the for loop and tried to store it with +=, but that just puts all the links in one line, making it impossible for me to check each link separately.

Is it possible to even detect wether my page has the same a href links with the way I've set my code up or do I have to try something els?

I'd appreciate any comments that would help me out.

Thank you in advance!

EDIT: My intention is to remove one of the two articles, so the parent div that the link is in.

Upvotes: 1

Views: 572

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370769

You could make a Set of the .top-post a's hrefs. Then, when you iterate over the .tiles, check to see whether the Set includes the href of the item you're iterating over:

const topHrefs = new Set(Array.prototype.map.call(
  document.querySelectorAll('.top-post .post-title a'),
  a => a.href
));
document.querySelectorAll('.tiles .post-title a').forEach((a) => {
  if (topHrefs.has(a.href)) {
    console.log('duplicate found: ' + a.href);
    // To remove the parent element of a found duplicate:
    a.parentElement.remove();
  }
});

Upvotes: 2

Related Questions