When CSS fails, use JavaScript

image.png

One of the fun things about having a bunch of smaller clients is the amount of variety in my day to day.

I love to solve these puzzles!

Today a client asked how they can hide specific links in their blog sidebar. Not the whole widget, just specific comments that relate to podcast reviews (for some reason these links just look poop and the plugin developer wasn't helpful).

We both tried different ways to see if they could be filtered or given a specific css ID or class but no joy.

What about JavaScript I thought?

With JS you can traverse the document and look for strings. Another bit of tweaking and testing and I have the following:


// Select all anchor tags on the page
const links = document.querySelectorAll('a');

// Loop through the links and remove the parent <li> if the href contains "#review"
links.forEach(link => {
    if (link.href.includes("#review")) {
        const parentLi = link.closest('li'); // Find the closest <li> ancestor
        if (parentLi) {
            parentLi.remove(); // Remove the <li> from the DOM
        }
    }
});

First we get a collection of links from the page.

Our loop goes to each and looks for the telltale signal that we are looking at a podcast reviews.

I thought about using Parent but in researching I found closest instead, which is less precise but means we ignore some potential formatting upsets.

Now when we find the LI we can use remove() to remove the entire list item from the document.

Boom!



0
0
0.000
0 comments