Tips for locating the ID of an array element based on the text or value of the element

I am trying to identify the span id of elements in an array based on their values. For instance, if the value in the array is "Yellow", I need to determine that the corresponding span's id is "test4". However, I am struggling to figure out how to extract the span id from the text/value within the span tags.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <script type="text/javascript">
    function doFunction(){
    var myArray = ["Green", "Yellow", "Brown"];
    for (i = 0; i < myArray.length; i++) { 
    text = myArray[i];
    alert(text);
    }
    }
    </script>
    <title></title>
  </head>
  <body>
    <span id="test1">Red</span><br>
    <span id="test2">Green</span><br>
    <span id="test3">Blue</span><br>
    <span id="test4">Yellow</span><br>
    <span id="test5">Orange</span><br>
    <span id="test6">Brown</span><br>
<button name="button" onclick="doFunction()">Click Me</button>    
  </body>
</html>

Answer №1

function executeFunction(){
var colorsArray = ["Red", "Blue", "Orange"];
var spanElements = document.getElementsByTagName("span");
for (var i = 0; i < spanElements.length; i++) { 
       if(colorsArray.indexOf(spanElements[i].innerHTML) > -1){
           alert(spanElements[i].id);
       }
   }
}

Try it out: http://jsfiddle.net/4rZ5h/

This script utilizes indexOf, so it's recommended to have a polyfill for IE<9 compatibility

Answer №2

The best approach would be to start by obtaining a list of all the spans, possibly using the querySelectorAll method. Next, iterate through the list and check the innerHTML of each span to find any matches.

One way to retrieve the list is as follows:

// Locate all spans with `id` attributes starting with "test"
var spanList = document.querySelectorAll("span[id^=test]");

(It is recommended to assign a class to the spans and use that for selection instead of the attribute query.)

Then, within your loop through the values in your array, loop through the span list.

var index;
for (index = 0; index < spanList.length; ++index) {
    if (value === spanList[index].innerHTML) {
        // a match is found
    }
}

To consolidate the steps, consider the following:

function checkMatches(){
    var dataArray = ["Red", "Blue", "Orange"];
    var spanList = document.querySelectorAll("span[id^=test]");
    var index, value, j;
    for (j = 0; j < dataArray.length; j++) { 
        value = dataArray[j];
        for (index = 0; index < spanList.length; ++index) {
            if (value === spanList[index].innerHTML) {
                // this span meets the criteria
            }
        }
    }
}

Additional point: In the code snippet above, there are explicit var declarations for j and value. This practice helps avoid issues related to Implicit Global Variables.

Answer №3

If you iterate through each span element and check if they exist in your array, you can then display their ID if they do.

function checkSpans(){
    var colorsArray = ["Green", "Yellow", "Brown"];

    // Get all span elements
    var spans = document.getElementsByTagName('span');

    // Loop through each span
    for (var i = 0; i < spans.length; i++) {
        // Check if the value is in the array
        var index = colorsArray.indexOf(spans[i].innerHTML);
        // If it is
        if(index != -1){
           // Show the text and the ID
           alert(colorsArray[index] + ' : ' + spans[i].getAttribute('id'));
        }
    }
}

JS Fiddle

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

Node.js - Issue with res.json function: inconsistency across different routes

Currently working with the MERN stack (Mongo, Express, React, Node) and encountering an issue in my API. Here is a snippet from my plaid.js file where one of my routes is causing an error. I have omitted any sensitive information such as secret tokens, bu ...

Storing the radio button's selected value in local storage using Vue JS

I have a pair of radio buttons that are linked together to accept a boolean value, either true or false. I am trying to implement a functionality where the selected value is stored in local storage. For example, if true is chosen, then true will be saved i ...

Displaying live IP CAMERA feed using three.js

I am currently facing a challenge in rendering a video stream from an IP Camera to a three.js texture. I have attempted the following code snippet without success: .... var video = document.createElement('video'); video.crossOrigin="anonymous" ...

Angular 2: Enhancing Textareas with Emoji Insertion

I am looking to incorporate emojis into my text messages. <textarea class="msgarea" * [(ngModel)]="msg" name="message-to-send" id="message-to-send" placeholder="Type your message" rows="3"></textarea> After entering the text, I want the emoj ...

Sending JSON Data from C# to External JavaScript File without Using a Web Server

Trying to transfer JSON data from a C# (winforms) application to a static HTML/JavaScript file for canvas drawing without the need for a web server. Keeping the HTML file unhosted is preferred. Without involving a server, passing data through 'get&ap ...

Renew Firebase Token

Currently, my email and password authentication flow in web Firebase JavaScript involves generating a token that I then verify on my node.js backend using firebase-admin. To make things easier, I store this generated token in the browser's local/sessi ...

Can a double array be classified as an object?

Yesterday, we took a test and one of the multiple choice questions was: If you have the following variables declared in your code, how many objects would you have? double[] number = new double[6]; int number2 = 0; I selected 2 as my answer since there ...

Leveraging event listeners in conjunction with React's useEffect function

Check out the code example on Code Sandbox here Hey there, I'm trying to implement a feature where clicking a button inside a container displays a box. I've set up an event listener so that when you move your mouse outside the container, the box ...

The 'fetch' operation could not be completed on the current window due to a TypeError

The error message I am receiving is: TypeError: Failed to execute 'fetch' on 'Window' : The provided value is not of type '(sequence<sequence> or record<ByteString, ByteString>)'. My current challenge involves fetc ...

PHP AJAX Request Failing to Transfer Files

I am having trouble with sending files in a PHP AJAX Request: Here is the form code: <form class="frmContact" action="#" method="post"> <div class="col-md-6"> <input type="hidden" name="emailTo" id= ...

Sending two objects back in res.send() in an API: A step-by-step guide

I've got an API that looks like this router.get('/exist', async (req, res) => { try { const { user: { _id: userId } } = req; const user = await User.findById(userId); const profile = await Profile.findById(user.profile, &apo ...

Mystifying WebPack sourcemaps lead to duplicated files

Today, I decided to experiment with WebPack on a new project I'm starting and I'm encountering some unusual behavior with the sourcemaps. Despite checking the documentation and scanning through StackOverflow, I can't seem to find any helpful ...

Error: An unexpected symbol '||=' was found

I'm facing an issue while trying to create a nextjs project with PDFViewer using @react-pdf-viewer. The error I encountered is "SyntaxError: Unexpected token '||=' when collecting pages. This problem seems to be originating from pdf.js in t ...

Creating a decorative ribbon in three.js for your gift presentation

How can I create a ribbon for a gift box using three.js, similar to the example shown here: Is it possible to create the ribbon with just one piece or do I need multiple pieces to achieve the desired look? Thank you :) ...

The styles from the npm package are not being properly applied to the class

After creating my react npm package using webpack, I encountered an issue where the styles from the package were not being applied to classes when installed in my react project. I used style-loader in my webpack configuration, but kept getting errors sayin ...

Having trouble initiating the server using npm start

Just starting out with nodeJs: I have created a server.js file and installed nodejs. However, when I try to run "npm start", I encounter the following errors. C:\Users\server\server.js:43 if (!(req.headers &amp;& req.headers. ...

Creating a function to manipulate an element on a different webpage

Upon clicking a button on Page1, a function is triggered which then calls another function to generate HTML and append it to a div with the #lista id. The issue here is that #lista belongs to Page2, so I am unsure if there is a syntax similar to ajax where ...

How to clear a 24-hour-old template from the Angular 1 cache?

I have implemented the following rule to clear template cache in my AngularJS application: myApp.run(function ($rootScope, $templateCache) { $rootScope.$on('$viewContentLoaded', function() { $templateCache.removeAll(); }); }); Howe ...

Display hyperlinks upon hovering over text

In the sign-up form, there are options for two different types of users: teachers and students. When the sign-up option is selected, a drop-down menu with choices for teacher and student will appear. However, I would like it to function more like other w ...

Guide to adding the initial element in an array using Immutability Helpers

Looking to rearrange the elements in an array? The challenge is that it involves a link to the object. How can this be achieved using immutability helper? Below you will find my current code: state = { table: [['', '', ' ...