Display only certain links using CSS or JavaScript/jQuery within a widget that appears once the webpage is fully loaded

I'm currently facing an issue on a website that requires a solution involving jQuery/javascript, which I am not proficient in.

After the page loads, javascript is executed which renders various html/css elements. The specific portion we are focusing on appears like this:

<div class="profile-list">
<a class="profile-profile" href="https://website.com/?profile=joe_blogs_337#show_more">Add loads of html</a>
<a class="profile-profile" href="https://website.com/?profile=sam_smith_292#show_more">Add loads of html</a>
<a class="profile-profile" href="https://website.com/?profile=john_doe_31#show_more">Add loads of html</a>
<a class="profile-profile" href="https://website.com/?profile=stack_overflow_17#show_more">Add loads of html</a>
</div>

We only want to display certain profiles and ignore any that do not match our criteria.

I've attempted using CSS to hide individual profiles like so:

a.profile-profile[href$='?profile=stack_overflow_17#show_more'] {
    display: none !important;
}

I can also hide all profiles except one with the following code:

a.profile-profile:not([href$='?profile=stack_overflow_17#show_more']) {
    display: none !important;
}

However, when I try to hide all profiles except two, they all end up hidden...

a.profile-profile:not([href$='?profile=stack_overflow_17#show_more']), a.profile-profile:not([href$='?profile=john_doe_31#show_more']) {
    display: none !important;
}

Since CSS doesn't seem to be the answer, I'm seeking a quick javascript solution...

Is there a way to detect when the external js script runs so that it can modify the rendered HTML swiftly?

Instead of globally hiding all links and then selectively showing some, I'd prefer to find a more targeted approach using jQuery/Javascript.

Answer №1

To enhance the filtering of href links, consider creating an array of desired hrefs and utilize .filter() in conjunction with .indexOf() to either hide or show them.

If you are looking for specific strings

var a_Links = [
  "?profile=stack_overflow_17#show_more",
  "?profile=john_doe_31#show_more"
  // Add more expected href's .....
];
$('a').filter(function(){
  return a_Links.indexOf($(this).attr('href')) > -1
}).hide();  // To display, use `.show()`
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<a class="profile-profile" href="just">A Link</a>
<a class="profile-profile" href="?profile=stack_overflow_17#show_more">Another Link</a>
<a class="profile-profile" href="?profile=john_doe_31#show_more">Another 2 Link</a>

On the contrary, this targets links within the .profile-list element and finds if any of them match the strings in the array using the indexOf function.

var a_Links = [
  "?profile=stack_overflow_17#show_more",
  "?profile=john_doe_31#show_more"
  // Add more expected href's .....
];
$('.profile-list a.profile-profile').filter(function(){
  return contains(a_Links , $(this).attr('href').trim().toLowerCase()) !== 1;
}).hide();  // To show, use `.show()`

function contains(a , href) {
  var founded = 0
  for (var i = 0; i < a.length; i++) {
      if(founded == 1){break;}
      founded = (href.indexOf(a[i]) > -1) ? 1 : 0;
  }
  return founded;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="profile-list">
  <a class="profile-profile" href="just">A Link</a>
  <a class="profile-profile" href="link?profile=stack_overflow_17#show_more">Another Link</a>
  <a class="profile-profile" href="link?profile=john_doe_31#show_more">Another 2 Link</a>
</div>


<div class="another-profile-list">
  <a class="profile-profile" href="just">A Link</a>
  <a class="profile-profile" href="?profile=stack_overflow_17#show_more">Another Link</a>
  <a class="profile-profile" href="?profile=john_doe_31#show_more">Another 2 Link</a>
</div>

Answer №2

Give this a shot:

Here is an example code snippet that demonstrates how to selectively show/hide profile links based on specific profiles:
const profilesToShow = [
    '?profile=bob_smith_22#show_more',
    '?profile=alice_wonderland_45#show_more'
];

$('a.profile-profile').hide();

profilesToShow.forEach(profile => {
    $('a.profile-profile[href$="' + profile + '"]').show();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

search for the compose function in the material table within a react component

When I receive a string array as a response from the API for lookup, it looks like this: ['India', 'Sri Lanka'] I am looking to pass this as a parameter to a Material React table column as a List of Values (LOV) in the following format ...

Can you provide me the steps to delete the title attribute from images in Wordpress?

My client has expressed dissatisfaction with the tooltip that appears when hovering over images in certain browsers, particularly Safari. This tooltip displays the title attribute within the img tag, which is a requirement enforced by Wordpress. Even if w ...

Leveraging JavaScript to create a horizontal divider

Just a quick question - how can I create a horizontal line in Javascript that has the same customization options as the HTML <hr> tag? I need to be able to specify the color and thickness of the line. I am working on a website where I have to includ ...

The $scope.$watch function is not triggering events within a controller of a ui.bootstrap.modal

Currently, I am utilizing UI bootstrap for Angular and have successfully integrated the ui.bootstrap.modal component into my project. Everything seems to be working smoothly except for one issue I am encountering. Despite setting up a $scope.$watch to trac ...

Issue with React.useEffect not functioning in Express application

I'm having trouble with the state not updating or re-rendering in my code. I've tried logging from inside the useEffect function but nothing seems to happen. Any suggestions on how to make the useEffect work properly? app.js var createError = re ...

The module specifier "logrocket" could not be resolved, make sure to use either npm or

I'm currently having an issue with initializing LogRocket. I followed the steps from the official documentation: I successfully installed it using node: npm i --save logrocket However, when trying to initialize it on my page earlier with: < ...

Patience is key: techniques for real-time variable updates and calculations in JavaScript

Hi, I am currently working on creating a dashboard to calculate the total outstanding amount for my medicine suppliers using Next.js. Below is the code snippet for my "createPurchase" API: import PurchaseOrder from '../../models/PurchaseOrder' ...

Updating JSON data within JavaScript

Currently, I am in the process of developing a webpage that pulls data from a json feed. However, I am looking to have it update every 30 seconds without refreshing the entire page, just refreshing the Div & Jquery elements. I have attempted various solut ...

Using jQuery, you can store values in a PHP array or session by making an AJAX

Is there a way to store values in PHP array or PHP session using ajax in jQuery? I am trying to send some values via ajax to a PHP page and store them. The issue is that every time the array/session only returns the latest sent value, and not the previous ...

Guide to automatically loading a default child route in Angular 1.5 using ui-router

Hello, I am looking to set a default child route to load as soon as the page loads. Below is the code snippet: $stateProvider.state('userlist', { url: '/users', component: 'users', data:{"name":"abhi"}, resolv ...

Generate - Create 2 different versions of the web application

Currently, I am in the process of learning Grunt and exploring ways to generate 2 variations of an application with different configuration settings. My goal is to have one version where a boolean in a specific .js file is set to false, and another versio ...

Iterating through a JavaScript object

Just starting out with JavaScript and trying to figure out how to iterate through a JSON result that has been converted into a JavaScript object. const url = 'https://api.mybitx.com/api/1/tickers?pair=XBTMYR'; fetch(url) .then(res => re ...

Issue with triggering onclick event in both parent and child components

I am working with 2 components in Vue.js: An Accordion header that opens its content when clicked on. A Cog icon that opens a mini-modal menu. The issue arises when I click on the cog icon - I do not want the Accordion to open its content. Before click ...

What is the best way to incorporate navigation options alongside a centered logo?

Looking to create a unique top header layout with the logo positioned in the center and navigation options on both sides. Below is the initial code, but unsure how to proceed further. Any suggestions on achieving this design? <div class="header"> ...

npm WARNING: The package @angular-devkit/[email protected] is in need of a peer dependency xxxx, however no installation for this dependency has

Attempting to launch an angular project and encountering the following errors: $ npm install npm WARN @angular-devkit/[email protected] requires a peer of @angular/compiler-cli@^14.0.0 but none is installed. You must install peer dependencies yoursel ...

Tips on how to adjust the HTML5 input type attribute in ios 5 to display the current date and time

I attempted the solution that seemed most straightforward, but unfortunately it didn't yield the desired outcome... const element = document.getElementById("element-id"); element.value = new Date().toString(); The code requires a string input, but h ...

What is the process of uploading a video and showcasing it on an HTML page?

I have successfully uploaded images and displayed them on an HTML page. Now, I am looking to do the same for videos. Here is my current code: $('#addPhotosBtn').click(function() { $(this).parents().find('#addPhotosInput').click(); }) ...

I envision my home page being divided into two visually stunning full-screen sections, each taking up the entire height of the page

I am currently working with the code shown below. It successfully displays the first part in full height, regardless of resolution, but once I scroll to the second half, there is a large empty gap. How can I eliminate this gap and make the transition smoot ...

how to use jQuery to locate the immediately preceding node that meets specific criteria

How can I locate the nearest parent node above $(this) node that has a specific property such as class="field", without considering parent/child relationships? ...

What is the best way to ensure that my ajax key/values are properly identified within the "params" object in a controller?

Attempting to send data using JQuery ajax to a grails controller Here is the data: var data = {'status':"SOMETHING", 'scheduleDate':remindDate.toString("MMMM dd yyyy h:mm:ss tt"), ...