Retrieve the class using a text string and then obtain the subsequent string

I am searching for the first class containing the text "Routed:" and then I want to retrieve the following string. I attempted to utilize document.querySelector, but I'm uncertain if this is the correct approach.

<td class="msvb2">Routed:</td>
<td class="msvb2">AAZ12332</td>

Edit update:

var tds = document.getElementsByClassName('ms-cellstyle ms-vb2');

var value, index = 0, length = tds.length;

for ( ; index < length; index++) {

-   if (tds[index].textContent == 'Routed:') {

-         value = tds[index].nextElementSibling.textContent;

- break;
- }
}
document.getElementsByClassName('ms-cellstyle ms-vb2').textContent = value;

console.log(textContent);

When running this script, I encounter the error:

Uncaught ReferenceError: textContent is not defined

Answer №1

To achieve this task, you can gather all elements with a specific class and examine their content to locate a match. Once a matching element is found, you can retrieve the content of its next sibling.

Check out this Fiddle for an example: http://jsfiddle.net/abc123xyz/1/

var elements = document.getElementsByClassName('sampleClass');
var value, index = 0, totalElements = elements.length;
for ( ; index < totalElements; index++) {
    if (elements[index].textContent == 'Target Text:') {
        value = elements[index].nextElementSibling.textContent;
        break;
    }
}

Answer №2

To extract all the td elements, iterate through each of them and check if their textContent matches a specified search string. If found, return the value of the following node within the loop.

function retrieveNextValue (searchCriteria) {

  var nextData = '', tableData = document.querySelectorAll('td');

  for (var index=0; index < tableData.length; index++) {
    if (tableData[index].textContent === searchCriteria) {
      return tableData[index+1].textContent;
    }
  }
};

console.log(   retrieveNextValue('Routed:') );

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

Analyzing data visualization within CSS styling

I have the desire to create something similar to this, but I am unsure of where to start. Although I have a concept in mind, I am struggling to make it functional and visually appealing. <div id="data"> <div id="men" class="shape"></di ...

Ensure that the placeholder remains visible as you type in the input field

Is there a way to implement an input text field in React with the placeholder "DD-MM-YYYY," that partially disappears as I start typing? For example, when I type "02-," only "-MM-YYYY" should remain visible as part of the placeholder. ...

Tips for customizing the appearance of date circles and text in Vue V-Calendar.io

On v-calendar.io, there is a demo showcasing the correct display where the date "2018-01-01" has a red background and dark text: However, my display does not match that. I have included Vue.js and v-calendar through CDN, and the page is formatted in HTML ...

Experience seamless slide transitions with the react-slick carousel using scroll events in React JS and JavaScript

Currently utilizing the carousel library found at: react-slick I am interested in enabling mouse scroll functionality to navigate through each slide. The idea is to scroll up to progress forward and scroll down to go backward. Came across a relevant exa ...

Guide to dynamically setting SCSS $variables in JavaScript after retrieving them from local storage in a React application

In my current situation, I am retrieving color combinations in hash values from the database through an API call and then saving them in localStorage for future use. However, I am facing a challenge when trying to access this data from localStorage and uti ...

Is there a way to ensure that my AngularJS factory fetches HTTP data only once?

I have implemented a factory in my project to share data among multiple controllers. Here is the code for my factory: var szGetData = "some url that works"; myApp.factory('Data', function ($http) { var eventData = {}; eve ...

Losing authentication token when refreshing with Nuxt asyncData and Axios

While testing a get API that retrieves an array of mail data through Postman, everything seems to be working smoothly. However, when I implement the asyncData method to fetch the array in my code, it only works once. Upon page refresh, I encounter a 401 er ...

Using Vue.js, perform calculations on various fields within an array of objects generated by the v-for directive

I am currently learning Vue.js and I have implemented a v-for loop to iterate through an array of objects. However, I now need to calculate a specific field (precoPorKg) within this loop. In order to perform this calculation, the input item.quantidade mus ...

JavaScript can extract a portion of an array

Is it possible to generate a new array consisting of all elements ranging from the nth to the (n+k)th positions within an existing array? ...

Ways to organize JSON data from a fetch request into multiple divisions

I have written a JavaScript code to fetch JSON information. I plan on storing this JSON file locally (I downloaded an example file and added a birthdate object for my usage example from https://jsonplaceholder.typicode.com/users) My goal is to parse the r ...

What is the best location to initialize Firebase in a React Native application?

What is the best way to initialize Firebase in a React Native project and how can I ensure that it is accessible throughout the entire project? Below is my project structure for reference: Project Structure Here is a basic template for initializing Fireb ...

The issue with EJS Header and Footer not showing up on the

I am currently building a basic todo list application using EJS. However, I am encountering an issue when running it. I would like to run app.js with the header and footer in EJS, but it seems that it is not recognizing the header despite using what I beli ...

Is there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

Which is the Better Choice for an MMO WebSocket Server: Node.js or C++?

Contemplating creating a live game using WebSockets for the web has been on my mind. With my knowledge of Node.js, it's tempting to develop it there. However, C++ appears to be the favored server language due to its speed. Would it be best to try bui ...

Avoid Scrolling within an iFrame in HTML with the Use of #

I have a menu loading in an iframe with links using # like http://<location>/page.html#part1. When I click inside the iframe, the entire page outside of the iframe scrolls to the location of #. How can I stop this from happening? I only want the me ...

Having difficulty accessing the ::after element on Firefox when attempting to click

I've encountered an issue with my HTML and CSS code - it functions perfectly on Chrome, yet behaves differently on Firefox. button#groupToggle { background: 0 0; border: 1px solid #e6e6ed; color: #222; float: none; margin: 0 0 ...

Is it possible to modify the express static directory path depending on the route being accessed?

I am trying to dynamically change the static path based on the route. Here is an example of what I have tried: const app = express(); const appRouter = express.Router(); const adminRouter = express.Router(); appRouter.use(express.static('/path/to/ap ...

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

Incorporate the ability to display a shape on a map when hovering over a table element, without the need to manually code a JavaScript function for every instance

I came across a script online that allows me to hover over text and have a shape appear on an imagemap. It's functional, but only works for a single instance. Is there a way to implement a JavaScript that handles individual instances so I don't h ...

Create dual modules within a single project

I am working on a mean-stack project. In my index.js, at the end, I have: router.get('*', function(req, res) { res.sendfile('./views/index.html'); }) module.exports = router; Now, I need to handle all webpages that match https://l ...