Identifying a span element and appending to its classList

I am currently working on code that generates spans, and my objective is to adjust the color of specific spans based on their text content. I have identified a section where I need assistance with the syntax of the code I should input. My aim is to locate the span by its text and append 'is-active' to its classList.

    <head>
        <style>
            .tagger1010 span 
            {
    padding: 6px 10px;
    background: #D0E8E4;
    border-radius: 18px;
    color: #000000;
    font-family: Roboto;
    font-size: 12px;
    margin: 0 4px 8px 0;
    font-weight: 500;
    display: inline-block;
    word-wrap: break-word;
    white-space: normal;
              cursor: pointer;
            user-select: none;
border: 1px solid BBD0CD;

            }
    
            .tagger1010 span.is-active {
                background-color: #008fde;
                color: #ffffff;

            }
            
            .tagger1010 span:hover {
                background-color: #008fde;
                color: #ffffff;
            }
        </style>

<body>
    
<div class="tagger1010">
  <span>Google</span>
  <span>Microsoft</span>
  <span>Facebook</span>
  <span>LinkedIn</span>
</div>

<div class="as-console-wrapper"></div>
<div class="as-console"></div>  
 <script type="text/javascript">
       const changeColor = (evt) => {
  if (evt.currentTarget.classList.contains("is-active")) {
    evt.currentTarget.classList.remove("is-active");
  } else {
    evt.currentTarget.classList.add("is-active");
  }
};
const EL_tagger1010_children = document.querySelectorAll(".tagger1010 span");
EL_tagger1010_children.forEach(EL => EL.addEventListener("click", changeColor));

var tags = ["Microsoft","Facebook"];
var spans = div.getElementsByTagName("span");

for(i=0;i<tags.length;i++)
{
  if(spans.includes(tags[i])){
  //Locate the span containing the text 'tags[i]' and apply 'is-active' to its classList
 }
 }
    </script>
    
    <div class="as-console-wrapper">
    <div class="as-console">
    
</div>
</div>
</body>
</html>

Answer №1

Consider the scenario where

div.getElementsByTagName("span");
is replaced with
document.getElementsByTagName("span");
, you can then experiment using the filter() method as shown below:

var s = [...spans].filter(j => j.textContent == tags[i])[0];
if(s){
  s.classList.add('is-active')
}

Demo:

.tagger1010 span {
  padding: 6px 10px;
  background: #D0E8E4;
  border-radius: 18px;
  color: #000000;
  font-family: Roboto;
  font-size: 12px;
  margin: 0 4px 8px 0;
  font-weight: 500;
  display: inline-block;
  word-wrap: break-word;
  white-space: normal;
  cursor: pointer;
  user-select: none;
  border: 1px solid BBD0CD;
}

.tagger1010 span.is-active {
  background-color: #008fde;
  color: #ffffff;
}

.tagger1010 span:hover {
  background-color: #008fde;
  color: #ffffff;
}
    
<div class="tagger1010">
  <span>Google</span>
  <span>Microsoft</span>
  <span>Facebook</span>
  <span>LinkedIn</span>
</div>

<div class="as-console-wrapper"></div>
<div class="as-console"></div>  
  <script type="text/javascript">
    const changeColor = (evt) => {
      if (evt.currentTarget.classList.contains("is-active")) {
        evt.currentTarget.classList.remove("is-active");
      } else {
        evt.currentTarget.classList.add("is-active");
      }
    };
    const EL_tagger1010_children = document.querySelectorAll(".tagger1010 span");
    EL_tagger1010_children.forEach(EL => EL.addEventListener("click", changeColor));

    var tags = ["Microsoft","Facebook"];
    var spans = document.getElementsByTagName("span");

    for(i=0;i<tags.length;i++)
    {
      var s = [...spans].filter(j => j.textContent == tags[i])[0];
        if(s){
        //Find the span whose text is tags[i], and add is-active to it's classList
        s.classList.add('is-active')
      }
    }
  </script>
    
  <div class="as-console-wrapper">
  <div class="as-console">
    
</div>
</div>

Answer №2

Instead of simply checking if the spans include the tag, it would be more beneficial to identify which span actually matched it. One approach is to utilize a nested for loop:

for (i = 0; i < tags.length; i++) {
    for (j = 0; j < spans.length; j++) {
        if (spans[j].textContent === tags[i]) {
            spans[j].classList.add('is-active');
        }
    }
}

If you prefer a less verbose method:

for (var tag of tags) {
    for (var span of spans) {
        if (span.textContent === tag) {
            span.classList.add('is-active');
        }
    }
}

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

how to display ajax response in webpage using jQuery

I need to perform multiple ajax calls in a for loop, with each call returning a text/html response that needs to be printed. Here is the code I have implemented: function printBill(printBills, lastBillNo, type,taxType,outletId,date){ var printableObjects ...

AngularJS: Patience for an asynchronous request

I'm having trouble understanding the concept of promises in AngularJS. Here is a provider I have: var packingProvider = angular.module('packingProvider',[]); packingProvider.provider('packingProvider',function(){ ...

Tips on accessing the text content of a dt element with prototype

Below is some HTML code that I am working with: <dl> <dt><label>test</label></dt> <dd><input id="someid" type="checkbox" onchange="opConfig.reloadPrice()" class="product-custom-op ...

Is it possible to assign a predetermined text content to a table cell using a CSS class?

I attempted the following: <style type="text/css"> td.orange : before { background: #DD5F15; content : "TRIPLE";} </style> However, it seems that the content is being added after the closing "td" tag, which is causing it not to display. E ...

The web server experiences a layout and functionality breakdown caused by an issue with the config.js file following the uploading process

I recently created a website. However, when I uploaded it to my hosting company's server and tested it on different browsers, the layout appeared broken. Some of the CSS files loaded properly, but certain elements and styles were not in their correct ...

Animating SVG fills based on height using JavaScript

I am looking to create an animated gradient effect using JavaScript instead of CSS. I want the gradient animation to change based on the height in both SVG elements. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="200" height="20 ...

What is the best way to optimize my ExpressJS + Sequelize files for proper compatibility with Jest testing framework?

For the past few years, I have been developing an ExpressJS server application for internal use at my workplace. This application serves as a clinical decision support tool utilized in various hospitals. As the application has grown significantly in size, ...

Looking to incorporate an additional column 'LastName' that can be used for filtering in the Angular data table code. This column will be included if it is present in the data

function applyFilter(filterValue: string) { filterValue = filterValue.toLowerCase(); --- return filtered result return this.dataSet.filter( (item: any) => item.name ? item.name.toLowerCase(). ...

`Is there a way to transfer a GUID from a View to JavaScript?`

I need to pass a GUID as a parameter from a View to a JavaScript function. However, I encountered an error message in Firefox stating "identifier starts immediately after numeric literal." Below is the code snippet from the View: onchange="updateOrder(&l ...

Choosing specific information in Typescript response

I am encountering an issue with my HTML where it displays undefined(undefined). I have checked the data in the debugger and I suspect that there may be an error in how I am using the select data. Here is a snippet of the code: <div *ngIf="publishIt ...

Incorporating JavaScript unit tests into an established website

I am facing a challenge with testing my JavaScript functions in the context of a specific webpage. These functions are tightly integrated with the UI elements on the page, so I need to be able to unit-test the entire webpage and not just the functions them ...

What is the best way to showcase a component using FlatList?

Discovering the power of React Native combined with TypeScript and Redux Toolkit Hello! I'm currently facing an issue with rendering a list of messages using FlatList. Everything renders perfectly fine with ScrollView, but now I need to implement inf ...

Make sure to use jQuery to fill in any missing HTML tags in dynamic content

Can someone assist me in identifying elements on my webpage that are not properly enclosed within HTML tags? For instance, consider the following situation: This is the picture of my village <img src="path_to_image" <br> some other text..... In ...

Designing webpages by superimposing text onto images with customizable positioning

My current project involves developing an HTML document with a floor plan image as the main layer. On top of this image, I need to display employee names extracted from a database and positioned on the map based on a location variable within the database ...

How can I convert the left links in my navigation bar to a CSS drop-down menu to make it more responsive on small screens?

Here is the structure of my HTML (at the top): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></s ...

Ways to resolve axios promise

My current task involves working on a GET request from an API. Upon receiving the response shown in the image, I noticed that the data presented in the promise is accurate. My goal is to display the letters and their corresponding promise data within the H ...

Custom stylesheet for individual users?

On my website, users can pick a template for their webpage. After selecting a template, I would like them to have the ability to customize certain styles like the font color. Is there a way to achieve this? I was thinking about saving the user's cus ...

Restricting the embedding of my website to a select few domains

Looking to embed my web app on various websites, but I want to restrict access based on domain. For example, allowing and to embed without issues, while blocking . Is there a way to achieve this? Using iFrames for the embedding process. ...

Is there a way to enclose a set of elements that are aligned to the

I am facing an issue with a container div that contains multiple items. The container requires a border, but the problem arises when I float the elements left within the container, as it seems to disrupt the flow of the elements. Adding a border to the co ...