Ways to change a CSS rule for a class when the data-attribute value aligns with an anchor tag's value?

Looking to incorporate read more links into various sections of a WordPress page, where clicking the link reveals content hidden with CSS. Here are a couple of sample sections in HTML format that I aim to replicate:

Section 1:

<p>Curious about what type of gifts to give employees? <a class="more-link-pwp" href="#" data-more-link-id="1">Read More.</a></p>
<div class="more-content-pwp" data-more-content-id="1">Find out how much to spend and whether corporate branding is necessary for employee gifts. Our expert team will assist you in selecting unique and memorable gifts for your staff.</div>

Section 2:

<p>Enhance employee engagement and impress new hires through meaningful and memorable gifts. <a class="more-link-pwp" href="#" data-more-link-id="2">Read More.</a></p>
<div class="more-content-pwp" data-more-content-id="2">Every gift makes an impact, from empowering underserved women to supporting sustainability efforts. Our Impact Booklet shares inspiring stories, offering a unique experience for gift receivers.</div>
<p>&nbsp;</p>

Using identical classes for both sections, I assigned specific IDs (data-more-link-id="1" and data-more-content-id="1") to target each section individually. However, my current jQuery code seems to have an error. Can someone assist me in rectifying it?

$('.more-link-pwp').click(function() {
  // fetch data-more-link-id
  var dataMorelinkid = $(this).attr("data-more-link-id");
  // retrieve data-more-content-id 
  var dataMorecontentid = $(.more-content-pwp).attr("data-more-content-id");
 
  // Loop through dataMorecontentid.
  for (let i = 0; i < dataMorecontentid.length; i++) {
   if (dataMorecontentid[i] == dataMorelinkid) {
   // Alter CSS for classes matching data-more-content-id with data-more-link-id.
      $('.more-content-pwp').css('display', 'block');
      $(this).css('display', 'none');
      return false;
   }
});

CSS:

.more-content-pwp {display: none;}

The goal is to only display the hidden content relevant to the clicked read more link, without revealing content from other sections sharing the same class.

Answer №1

$('.more-link-pwp').click(function() {
  // retrieve data-more-link-id
  var dataMorelinkid = $(this).attr("data-more-link-id");

  $(this).hide(); // update 1
  $(".more-content-pwp").each(function(){
     // $(this).hide(); // update 2
      const id = $(this).attr('data-more-content-id');
      if(id == dataMorelinkid){
      $(this).show();
      }
  });  
  
  });
.more-content-pwp{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>What kinds of gifts should you give employees? <a class="more-link-pwp" href="#" data-more-link-id="1">Read More.</a></p>
<div class="more-content-pwp" data-more-content-id="1">How much should you spend? Should corporate gifts for employees be company-branded? Our expert team will help you choose memorable, unique gifts for your employees and office staff.</div>

<p> Deepen employee engagement and impress new hires while giving employee gifts that are meaningful and memorable. <a class="more-link-pwp" href="#" data-more-link-id="2">Read More.</a></p>
<div class="more-content-pwp" data-more-content-id="2">From empowering underserved women with job skills to supporting sustainability efforts every gift creates an impact. Our Impact Booklet showcases these inspiring stories, providing a unique experience for gift recipients.</div>
<p>&nbsp;</p>

The line below will return a string instead of an array.

var dataMorecontentid = = $(.more-content-pwp).attr("data-more-content-id");

The following code is functional.

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

Interactive navigation through scrolling with PHP onchange event

I need help with a PHP-related issue. I have a list of products that are generated dynamically using PHP. When a user clicks on one of the items in the list, the products are sorted. I also want the user to be smoothly scrolled to a new section of the page ...

Decoding jQuery serialized data in PHP

I am working with a form that is receiving data from the Google LocalSearch API. Users can select specific results by checking checkboxes I am adding to the form using jQuery. Here's an example of what the checkbox value might look like: title=Emijea ...

Setting the state to an array of objects in React: A beginner's guide

Currently, I am developing a flashcard application using React. To store the data entered by the user, I have initialized my state as an array of objects that can hold up to 10 terms and definitions at a time: state = { allTerms: [ { ...

The node.js API request is experiencing a unresponsive state

As a newcomer to the world of JavaScript, I am currently learning the basics of Node.js. One task I'm working on involves retrieving a contact from my mongoDB and creating a GET method to return it. Sounds simple, right? Below is the router method I ...

Changing a string to uppercase and lowercase

I am currently working on a software that takes a string, divides it, capitalizes the first letter of the first string, and capitalizes all letters in the second string. Below is the code snippet: var fullName = "ThEoDORe RoOseVElT"; function nameEditor( ...

Acquiring MySQL information and storing it in a variable array

Currently, I am retrieving data from MySQL with $username and $chance. The data contains two usernames but only the first one is being loaded. var data = [ { "name" : "<?php echo $username; ?>", "hvalue" : <?php echo $chan ...

What are some ways to create a responsive Grid in React JS with the help of Bootstrap?

Utilizing bootstrap in my react js project, I am implementing css grid to showcase some cards. However, I am encountering responsiveness issues. import React from "react"; import "./Project.css"; export const Project = () => { return ( <div& ...

Experiencing issues and alerts when handling JSON data

Here is the Json data I am attempting to represent using Json-LD : var schemaOrg = angular.toJson({ "@context": "http://schema.org", "@type": "RealEstateAgent", "RealEstateAgent": { ...

The essence of a character undergoes a complete transformation once it is presented in

There seems to be an issue with the character "т", ascii code: 209 130 When this particular character is put in italics, its appearance changes drastically... Check out the т character in italics (take a look at the source code - it's fascinating) ...

Styling spellcheck errors in Chrome with CSS or JavaScript

One issue I am facing is the need to change the language of a spelling error on a website without disabling it: I have attempted various solutions, but none of the properties like ::spelling-error and :webkit-spell-check seem to be supported. Is there a ...

The PHP form is all filled up with ones once it has been submitted

I am struggling.... Recently, I developed a PHP form that collects user information and sends it to the website owner. However, after submitting the form, the fields automatically populate with a '1'. This seems to indicate that the field was tr ...

Create text that remains hidden behind an image while ensuring the content stays fully

In my website design using HTML/CSS, I am working on achieving a specific layout goal: https://i.sstatic.net/6UUwK.png My aim is to have a div of text positioned behind an image. Although I have successfully accomplished this on a laptop screen, I am fac ...

How can one determine the most accurate box-shadow values?

I am trying to extract the precise box-shadow parameters from a CSS style rule generated by the server. My main focus is determining whether the element actually displays a visible shadow or not. There are instances where the shadow rule is set as somethi ...

Variable in SCSS not being applied as expected

I'm currently grappling with understanding why my alterations to the system colors aren't reflecting as expected. When viewing in Chrome, this is the image I see. https://i.sstatic.net/H6YbW.png However, this is what I anticipate should be vis ...

Using jQuery to target all rows and select the input within a td

I am attempting to calculate the values within a table by capturing changes in the input fields. Below is an example of the HTML table being addressed and the jQuery code I am using to extract values from all input fields by iterating through the rows usin ...

passport not initializing session with requests

I am currently utilizing passportJS for managing login and persistent sessions on the server backend. While everything functions properly when sending requests from the server frontend (a webpage that I didn't create and lack sufficient knowledge to ...

Is using display:table an effective approach for achieving equal height columns?

I am currently working on a responsive design project and I need two columns of equal height. I do not want to rely on JavaScript for this, and I prefer having some whitespace between the columns to enhance readability. I have tried two different layouts; ...

Tips for ensuring Node.js waits for a response from a substantial request

When uploading a large number of files, the process can take several minutes. I am currently using a multi-part form to post the files and then waiting for a response from the POST request. However, I am facing issues with timeouts and re-posting of files ...

Adding a link to a specific word in text using JavaScript or PHP

I am seeking a solution for how to automatically add a link to a specific word in text using PHP or JS. For instance: I want to insert a link for each occurrence of the word "lorem" in the text. such as: <a href=https://wwww.google.com/>lorem</ ...

Ways to apply the jQuery .on() method using vanilla JavaScript and document query selectors

How can we achieve the functionality provided by jQuery's on() function – allowing DOM events to trigger on elements that might be added in the future – using plain JavaScript? Specifically, how can we handle a mouseenter event on elements with a ...