Locate every div element that contains a span id matching any word in a specified list

I'm attempting to create a script that will add a class based on whether or not a list item's span id contains certain words from a list.

The list follows this structure:

<div id="main_list">
    <li class>
        <a data-item_number_id="555000" class="item"  <span id="displayname">greyblackhammer</span></a>
    <li class>
        <a data-item_number_id="555002" class="item"  <span id="displayname">grey_green_hammer</span></a>
    <li class>
        <a data-item_number_id="555004" class="item"  <span id="displayname">red_orangehammer</span></a>

This list contains thousands of entries.

Let's assume I have:

var list_of_words = ["Green", "black", "other_words"]

The goal is to search through the span ids and if they contain any of the strings in the list of words, add a "starred" class to their parent, as shown in this example:

 <div id="main_list">
    <li class ="starred">
        <a data-item_number_id="555000" class="item"  <span id="displayname">greyblackhammer</span></a>
    <li class="starred">
        <a data-item_number_id="555002" class="item"  <span id="displayname">grey_green_hammer</span></a>
    <li class>
        <a data-item_number_id="555002" class="item"  <span id="displayname">red_orangehammer</span></a>

Case and spacing are both irrelevant - the focus is on whether the span id contains the desired string in any form.

Since I'm not very knowledgeable in jQuery, I haven't made much progress. Here's what I have so far:

 ids_to_star = ["Green", "black"];

 function star_matching_span_ids(){

var matching_ids = $('#main_list').find("div:contains(ids_to_star)");
   $.each(matching_ids, function (){
       $(this).parent('li').addClass('starred');
   });
}

Unfortunately, this code doesn't work as expected and fails to select the span ids correctly. I would appreciate any guidance you can provide.

Answer №1

It appears that there are some errors in your HTML and JavaScript:

  1. Your HTML code is missing closing tags for the a and li elements.

  2. In your JavaScript, you have declared a function but have not called it, which means it will not function as intended.

  3. When using the find function, it is advisable to search within elements that are higher in the hierarchy. Additionally, the contains parameter should contain a string, not an array. Here is an example:

    ids_to_star = ["green", "black"];
    
    function star_matching_span_ids() {
    
    var matching_ids = $('').find("div:contains("+ids_to_star[0]+")");
       $.each(matching_ids, function (){
          $(this).parent('li').addClass('starred');
       });
    }
    

For a working example, you can refer to the following link: https://jsbin.com/donuzozemo/1/edit?html,js,output

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

Error message: The function for the AJAX call is not defined

I'm currently working with jQuery's ajax function and encountering an error: 'getQty is not defined' Can you spot my mistake here? jQuery Code: function getQty() { var dataString = "itemId=" +$(".itemId").val(); $.ajax({ t ...

The functionality of hiding and displaying div elements is malfunctioning

I am currently working on a side menu that contains two buttons. My goal is to display the content of the profile div by default, and when the user clicks on the My reviews button in the sidebar, I want to hide the content of the profile div and show the r ...

Error with the jQuery scrolling plugin

Currently, the script is set up this way: jQuery(document).ready(function(){ var windheight = jQuery(window).height(); var windTop = jQuery(window).scrollTop(); var windbottom = windheight + windTop ; jQuery.fn.revealOnScroll = function(){ return this.e ...

Steps to customize the default thumbnail image of an embedded video that is not from YouTube

I've added a video to an HTML page. Here is the code: <div> <video width="400" controls> <source src="videos/myvideo.mp4" type="video/mp4"> </video> </div> Is there a way to modify the default thumbnail image of ...

creating an animated loop within an Angular template

How can we display a dynamic loop in Angular template using an array of object data? [ { "name": "name", "text": "text", "replies": [{ "name": "Reply1", "t ...

Is it possible to accomplish this straightforward task using PHP?

Essentially, my goal is to have the content inside the h1 tag duplicated in the h2 tag as well. Take a look at the example provided below. <!DOCTYPE html> <html> <body> <h1>The content here should also appear in the H2 tag.</h1 ...

Adjust the pagination length within the jQuery DataTables plug-in

I am looking to customize the pagination length in DataTables plug-in for jQuery. Specifically, I want to calculate the number of pages on the server side and display the correct amount of buttons on the client side. Can anyone provide guidance on how to ...

Adding HTML to a webpage through the use of JavaScript's .innerHTML functionality

Currently in the process of creating a website template, I have made the decision to experiment with using an external JS file for inserting HTML at the top of the page to streamline navigation (eliminating the need for manual copying and pasting). My att ...

The positioning of drawings on canvas is not centered

I'm facing an issue while attempting to center a bar within a canvas. Despite expecting it to be perfectly centered horizontally, it seems to be slightly off to the left. What could possibly be causing this discrepancy? CSS: #my-canvas { border: ...

Sending FormData from React.js to an Express.js backend results in loss of data

I encountered a problem while developing a book library management CRUD system using React v18. The issue arises when attempting to add data to my MongoDB Atlas database. Whenever I pass the formData to axios.post through Redux, the req.body on the backend ...

Ensure that the value is updated upon clicking on the radio buttons and store the value in a session variable for

I'm working on a feature that involves two radio buttons: one for shipped and the other for not shipped. The requirement is that when the first radio button is clicked, an amount of 100 should be added to the total price. If the second radio button is ...

Is it possible for me to insert a hyperlink that will show a PDF in a web browser without triggering a download?

I am looking for a way to allow visitors to my website to easily access and view a PDF directly in their browser by clicking on a specific URL or button. I want the PDF to be displayed within the browser itself, rather than prompting a download. Any guidan ...

Incorporating PlayN games into an HTML/JS application

I've been considering creating a game using PlayN. While it's great for the game itself, I would rather handle menus, navigation, high-score lists, etc in HTML (possibly with GWT). If I develop a game using PlayN, are there ways to integrate it ...

React and Material UI: Ensuring Proper Whitespace Handling in Strings

Exploring the use of Typography component from Material UI (https://material-ui.com/api/typography/) The main objective is to maintain the new lines and spaces in a saved string. For instance, if the string contains leading spaces and new lines, it shoul ...

Combine all div elements to create a unified image and then proceed to save it as a jpg file before uploading to the server

These are the divs below: <div style="width:800px; height:420px; position:absolute; top:0px; left:0px; z-index:10; background-image: url('https://3t27ch3qjjn74dw66o1as187-wpengine.netdna-ssl.com/wp-content/uploads/2016/05/052516-800x420-vege-Wallp ...

Tips for achieving a seamless appearance with box-shadow on the left and right sides of various elements

.row { height: 300px; width: 300px; margin: 0 auto; box-shadow: 0 -20px 0px 0px white, 0 20px 0px 0px white, 12px 0 30px -4px rgba(0, 0, 0, 0.3), -12px 0 30px -4px rgba(0, 0, 0, 0.3); } <div class="row"></div> <div class="row">< ...

The craft of masonry is known for its creation of intentional gaps

I've gone through all the posts related to this issue, but none of the suggested solutions seem to work for me. Here is a visual representation of my grid: https://i.sstatic.net/ybufk.png If you want to see the code and play around with it, check o ...

Unable to pass data from a Jquery ajax request to another function

I've written a basic ajax request using jQuery. Here is the code for my ajax function: var sendJqueryAjaxRequest = function(arrParams) { var request = $.ajax({ url: arrParams['url'], async: false, ...

Having trouble getting Bootstrap 4 SCSS overrides to take effect?

Let's dive into a quote from the Bootstrap documentation: Each Sass variable in Bootstrap 4 comes with the !default flag, allowing you to modify the default value in your own Sass even after that original variable has been set. Here is the content ...

Having issues with passing POST data during file handling operations

I am attempting to utilize Ajax POST on my WordPress website to check if checkboxes are selected and update their values in the database upon clicking a button. Although using the standard PHP form submission is the simplest method, the fields that I need ...