Attempting to apply a class to selected elements, however, the conditional statement is not functioning as intended

<div>
<div class=category> Special Occasions </div>
<div class=category> Holidays </div>
<div class=category> Graduations </div>
<div class=category> Retirements </div>
</div>

<ul>
<li class="product-filter-items">Special Occasions</li>
<li class="product-filter-items">Retirements</li>
<li class="product-filter-items">Graduations</li>
<li class="product-filter-items">Holidays</li>
</ul>

<script>
    let proCatList = document.querySelectorAll(".category")
    
    let proFilterItems = document.querySelectorAll(".product-filter-items")        
    
    for(let i = 0; i < proFilterItems.length; i++){
    
        proFilterItems[i].addEventListener("click", function(){        
        
            if (proCatList[i].textContent.toUpperCase().replace(/[\n\r]+|[\s]{2,}/g, ' ').trim() == proFilterItems[i].textContent.toUpperCase().replace(/[\n\r]+|[\s]{2,}/g, ' ').trim()){
    
                proFilterItems[i].classList.add("active-filter")
                console.log("Class Added")
            }
        })  
    
    }
</script>

I am attempting to apply a class when clicked. My goal is to add the class "active-filter" if the category name matches the product filter item clicked. Can anyone assist in identifying why the textContent of proCatList is not being recognized in this statement?

Answer №1

The iterator parameter i cannot be utilized in the event handler. Instead, you can access the index of the clicked element by using this.

To obtain the index, you can employ this concise function:

const getIndex = elem => [...elem.parentNode.children].indexOf(elem);

See the functional demo below:

let proCatList = document.querySelectorAll(".category");
let proFilterItems = document.querySelectorAll(".product-filter-items");

/* Function to get the index */
const getIndex = elem => [...elem.parentNode.children].indexOf(elem);

for (let i = 0; i < proFilterItems.length; i++) {
  proFilterItems[i].addEventListener("click", function() {
    const elem_index = getIndex(this);
    
    if (proCatList[elem_index].textContent.toUpperCase().replace(/[\n\r]+|[\s]{2,}/g, ' ').trim() == this.textContent.toUpperCase().replace(/[\n\r]+|[\s]{2,}/g, ' ').trim()) {
      this.classList.add("active-filter");
      console.log("Class Added");
    }
  })
}
<div>
  <div class=category> Birthdays </div>
  <div class=category> Anniversaries </div>
  <div class=category> Newborns </div>
  <div class=category> Weddings </div>
</div>

<ul>
  <li class="product-filter-items">Birthdays</li>
  <li class="product-filter-items">Weddings</li>
  <li class="product-filter-items">Newborns</li>
  <li class="product-filter-items">Anniversaries</li>
</ul>

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

Dealing with client-side exceptions in a Next.js 13 application's directory error handling

After carefully following the provided instructions on error handling in the Routing: Error Handling documentation, I have successfully implemented both error.tsx and global-error.tsx components in nested routes as well as the root app directory. However, ...

Is there a way to automatically recalculate the "Total Price" when the input values are adjusted?

Whenever I add an item to the cart, it gets appended to the row in the shopping cart, and the price adjusts accordingly. However, I'm having trouble getting the price to adjust whenever I change the input values (input type: "number"). I can't se ...

Can the rxjs take operator be utilized to restrict the number of observables yielded by a service?

As someone who is just starting to learn Angular, I am working on a website that needs to display a limited list of 4 cars on the homepage. To achieve this, I have created a service that fetches all the cars from the server. import { Response } from &apos ...

experiencing difficulty in transmitting HTML content through nodemailer

I'm having trouble sending HTML-formatted text in emails using nodemailer. exports.send = function(req, res) { console.log(req.query); var mailOptions = { to: req.query.email, subject: req.query.sub, text: 'Date of Interview: ' ...

What could be causing my middleware to run twice?

A custom middleware was created in express.js/node.js to handle session checking. If a user ID is found in the session, it displays the user's menu; otherwise, it shows the default menu. For every page request, an ID check is performed and the user d ...

Exploring characteristics using DocumentTraversal

My goal is to list out the attributes of elements using DocumentTraversal specifically for IE11. While I have been successful in enumerating element attributes, I am facing an issue when trying to do the same with attributes. The enumeration stops at the f ...

Under what circumstances is it possible to iterate through an empty array?

When defining arrays in JavaScript using Array(n), it creates an empty array. If I write the following code: Array(2).map((val) => console.log(val)) Nothing happens when running this code, but if I spread out the elements of the array into another a ...

Enhancing images by creating clickable sections in a more organized and efficient manner

Are there any other methods to make parts of an image clickable in a more organized way, aside from using the coordinates method or directly embedding images from Photoshop? <script> new el_teacher = ["candice","john"]; $(".teacher1").mouseenter(fu ...

Unable to open fancybox from a skel-layer menu

Seeking assistance with integrating a Fancybox inline content call from a Skel-layer menu (using the theme found at ) <nav id="nav"> <ul> <li><a href="#about1" class="fancybox fancybox.inline button small fit" >about< ...

Is there a way to sort through a data object using a state array in React?

I have found a solution! The code below now displays a functioning example. My latest project involves creating a React portfolio with a Filter system. Users can visit the portfolio page and choose filters (web design, development, etc.) to view specific ...

Failure of Ajax POST requests to refresh screen content

Within my "scenario", I have numerous "forms" that consist of various "events," "data," and more. To populate all this information, I've included the following script to run once the page has fully loaded: $(document).ready(function() { var scenarioI ...

The script fails to execute on content loaded through AJAX in Django

I have a website with nested div elements that make up a complete set. These elements can be dynamically loaded when the user clicks the "load more" button. The website includes a script that changes the style of the aforementioned div element when the pa ...

The problem of a static click function not working when clicked on a link. What is the solution for this

Details I am currently using a flickity slideshow that automatically goes to the next picture on a click. Within the slideshow, I have placed a button with text and a link to an external website (e.g. ). My Problem: When I click on the link, my slidesho ...

Error: Angular7 Unable to locate namespace 'google'

I am currently utilizing the import { MapsAPILoader } from '@agm/core'; package to enable auto-complete address search functionality. However, I have encountered an error message stating cannot find namespace 'google'. The error occu ...

Accessing Data from Nested PHP Array in Javascript

My current situation is this: I have a MYSQL database that consists of two fields: 'ID' and 'string'. The 'string' field stores serialized arrays. To extract the data back, I utilize the following PHP code: $result = mysql_q ...

Oops! There was an issue while trying to serialize the props returned from getServerSideProps in "..." - we apologize for the inconvenience

Attempting to add a condition within getServerSideProps: export async function getServerSideProps(context) { const jwt = parseCookies(context).jwt || null; if (jwt) { const user = parseJwt(jwt); const userId = user.id; console.log(userId); ...

What is the process for enabling HLS.js to retrieve data from the server side?

I have successfully implemented a video player using hls.js, and I have some ts files stored in https:/// along with an m3u8 file. To read the content of the m3u8 file, I used PHP to fetch it and sent the data to JavaScript (res["manifest"] = the content ...

I am not forcing the Angular module to conform to my perspective

Hello, I am new to Angular and trying to experiment with some code. However, I seem to be stuck with the app.js file which is throwing an error: Uncaught SyntaxError: Unexpected token . Below is the structure of my application, which I obtained by cloning ...

Ways to set Material UI tabs as active exclusively for particular URLs

Looking for a solution to address a conflict arising from the active tab indicator being located on the right tab. Within my navbar, I have tabs leading to three different routes, two of which are quite similar. <Tabs indicatorColor="primary" ...

The error message "require is undefined for Electron"

I am developing an application that requires access to the file system (fs) module. Despite having nodeIntegration enabled, the renderer is throwing this error: Uncaught ReferenceError: require is not defined Many similar issues I researched suggested tu ...