How to use Vanilla JavaScript to toggle a click event on a list item (LI) that

I have a script that scans through a webpage and identifies a unique string, for example: multus –a –um. The page contains several <LI> elements with various text content, including instances of multus –a –um. I need a solution to locate an <LI> element on the page that contains a specific string, and then apply custom CSS changes to that particular element.

For instance:

  1. Execute the script and find: multus –a –um
  2. Search for the <LI> element containing multus –a –um
  3. Modify the background color of that element to #17af50

This functionality should be encapsulated within a function for ease of execution.

Answer №1

Discover the amazing Array methods available. They can greatly enhance your coding experience.

Array
  .from(document.querySelectorAll("li"))
  .filter(function(item){ return item.innerText.indexOf("foo") !== -1; })
  .forEach(function(item){ item.parentNode.classList.add("highlight"); });
.highlight { background-color: #17af50; }
<ul>
  <li>bar</li>
  <li>foo bar</li>
</ul>

<ul>
  <li>bar</li>
  <li>bar</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

Combining D3.js tooltip positioning with CSS overflow styling

I am encountering an issue with displaying tooltips in D3 when combined with CSS overflow. Is there a solution available for this particular problem? CSS code: #chart1 { overflow-x: auto; overflow-y: hidden; max-width: 800px; max-height: 22 ...

What is the best way to enhance an object using a class in ES6?

In an effort to improve the clarity of my ES6 class definition, my current code looks like this: class SomeClass { constructor({a, b, c, d, e}) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; // additional code here ...

Hide the 'white' color on visited links and category tags in the WordPress blog page

I created a custom WordPress theme, and I am having trouble styling the bootstrap navigation. I want the text to be white and change to brown when selected. However, my attempts to add a separate class for H1 tags on the blog post page have not been succes ...

Exploring the Mathematical Capabilities of jQuery

I have a question regarding a jQuery code that retrieves the price of Bitcoin from a JSON API and displays its current value in euros. I am interested in converting this to another currency, such as Danish Crown or any other. Essentially, my query is whe ...

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...

Navigating through a mergeMap observable with an undefined value

In my Angular 6 app, I have a class that attaches API tokens to every http request using the getIdToken() method. If the token retrieval is successful, everything works fine. However, if it fails, my app will stop functioning. I need help with handling th ...

The encoding for double quotation marks vanishes when used in the form action

I am attempting to pass a URL in the following format: my_url = '"query"'; when a user clicks on a form. I have experimented with encodeURI and encodeURIComponent functions as well as using alerts to confirm that I receive either "query" or %2 ...

Header on top of table that stays in place with scrolling

I'm facing an issue with a table that contains user-generated data. We are utilizing a plugin known as Clusterize, which allows us to smoothly scroll through large amounts of rows. However, the specific markup required for this plugin seems to be caus ...

Is JavaScript Promise Chaining Allowed?

I have a question regarding my code, despite it currently functioning correctly. Specifically, I'm wondering if the sequence of promises in my database is valid. Promise 1 must be fulfilled before moving on to Promise 2 because I rely on the data and ...

Iterate over the array and show the elements only when a click event occurs

I am trying to create a loop through an array (array) and display the elements one by one only after clicking a button (bt). However, when I run this code, it only shows the last element of the array (i.e. honda). Can someone please help me fix this issu ...

How to Route in Angular 5 and Pass a String as a Parameter in the URL

I am currently working on an Angular project that focuses on geographic system data. The concept is as follows: I have a component with the route: {path: 'home'}. I aim to pass a geojson URL along with this route, making it look like this: {pat ...

Shifting Angular Component Declarations to a New Location

Here's a question that might sound silly: In my Angular project, I am looking to reorganize my component declarations by moving them from angular.module.ts to modules/modules.modules.ts. The goal is to structure my src/app directory as follows: src ...

The functionality of the disabled and checked options on the radio button seems to be malfunction

Within an Angular HTML document, I have a set of radio buttons that share common names. I am attempting to update their disabled and checked properties from a .ts file, but the changes are not taking effect. Here is the code snippet: let elements = docume ...

Eslint problem: no-duplicates Fixing issue: cannot load resolver "node"

After performing an update on my project (a SPA using VueJS and Quasar Framework) today with npm update, I am encountering difficulties running it. An error message no-duplicates Resolve error: unable to load resolver "node" keeps appearing in various mod ...

Sending an email through Node.js with SendGrid is not a challenge

I've got this Mailer.js file const sendgrid = require('sendgrid'); const helper = sendgrid.mail; const keys = require('../config/keys'); class Mailer extends helper.Mail { constructor({ subject, recipients ...

Alert: Font preload was not utilized within a short timeframe after the window's load event

I've been working on optimizing the loading speed of fonts on my website, so I added the following: <link rel="preload" href="{{ '/css/fonts/bebasneue-webfont.woff' | prepend: site.baseurl | prepend: site.url }}" as="font" type="fo ...

Choosing a root element in a hierarchy without affecting the chosen style of a child

I am working on a MUI TreeView component that includes Categories as parents and Articles as children. Whenever I select a child item, it gets styled with a "selected" status. However, when I click on a parent item, the previously selected child loses its ...

Please submit information that is not already filled out in the text fields

I am looking to create a table with text fields and buttons as shown below: <table border="1"> <tr> <td>name</td> <td>id</td> <td>icon</td> <td> </td> & ...

The challenge of handling Set type in TypeScript errors

I'm currently facing two errors while trying to convert a function to TypeScript. The issue lies with the parameters, which are of type Set import type {Set} from 'typescript' function union<T>(setA: Set<T>, setB: Set<T>) ...

Dealing with encoding problems in Node.JS when parsing JSON data with UTF-

I have developed a small script that allows me to fetch keyword suggestions from the Google search API. One major issue I am facing is when the response contains special characters (such as à é ù etc.): my application returns unreadable keywords like: ...