using javascript to extract elements from an HTML table

I have some HTML code that I need help with.

<td class=​"style1 product name" valign=​"top" nowrap>23$​</td>​, 
<td style=​"padding-left:​10px;​" class=​"product name" width=​"85%">productY</td>​
<td class=​"style1 product name" valign=​"top" nowrap>​10$​</td>​, 
<td style=​"padding-left:​10px;​" class=​"product name" width=​"85%">productX</td>​

I attempted to use the script below, but it's returning the full HTML instead of just the product names:

document.getElementsByClassName("product name")

Can anyone provide me with guidance on how to modify this script so that it returns an array containing productX and productY?

Your help is greatly appreciated.

Answer №1

It's important to note that classes cannot contain spaces, so class=​"product name" is essentially defining two separate classes: product and name.

If you want to target elements with both the product and name classes but exclude those with the style1 class, you can use the query selector

document.querySelectorAll('.product.name:not(.style1)')
.

To extract the text content of each targeted element, you can iterate through the list like this:

var products = document.querySelectorAll('.product.name:not(.style1)'),
    a = [],
    i;

for(i = 0 ; i < products.length ; i++) {
  a.push(products[i].textContent);
}

console.log(a);
<table>
  <tr>
    <td class="style1 product name" valign="top" nowrap>23$</td>
    <td style="padding-left:10px;" class="product name" width="85%">productY</td>
    <td class="style1 product name" valign="top" nowrap>10$</td>
    <td style="padding-left:10px;" class="product name" width="85%">productX</td>
  </tr>
</table>

Answer №2

Feel free to give this a shot

let elements = Array.from(document.querySelectorAll(".product.name:not(.style1)"));

console.log(elements);
<table>
  <tr>
    <td class="style1 product name" valign="top" nowrap>23$</td>,
    <td style="padding-left:10px;" class="product name" width="85%">productY</td>
    <td class="style1 product name" valign="top" nowrap>10$</td>,
    <td style="padding-left:10px;" class="product name" width="85%">productX</td>
  </tr>
</table>

Answer №3

const items = document.getElementsByClassName("product name")
forms an array of elements with the class name product name. You can then access this array using indices like items[0] and so on.

The product name should be a single word like product-name to avoid having multiple classes in your td.

Answer №4

Consider the example where two classes are assigned to elements with class="product name". The first class is product, while the second one is name. In HTML, CSS classes should be separated by spaces. To improve this, you can use "product_name" instead (with an underscore).

HTML:

<td class=​"style1 product name" valign=​"top" nowrap>23$​</td>​, 
<td style=​"padding-left:​10px;​" class=​"product_name" width=​"85%">productY</td>​
<td class=​"style1 product name" valign=​"top" nowrap>​10$​</td>​, 
<td style=​"padding-left:​10px;​" class=​"product_name" width=​"85%">productX</td>​

Javascript:

document.getElementsByClassName("product_name")

Answer №5

When styling your product elements, remember to include the classname product-item:

var products = document.getElementsByClassName("product-items");
for (var i = 0; i<products.length; i++) {
    console.log(products[i].innerText);
}

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 Node and React: Using CSS Class Names with Hyphens

Currently, my project utilizes react-starter-kit and includes several react components, each with its own styling file (scss). Every component imports the styling file at the top like this: import s from './Header.scss'; When it comes to using ...

What is the best way to accurately determine the height and offset values of an element while utilizing ng-repeat?

My objective is to determine the offset and height of list items. Once I have those values, I trigger a function in a parent directive. Ultimately, this will involve transitioning elements in and out as they come into view. Issue: Due to the use of ng-rep ...

Unable to render Blender model in threeJS scene due to undefined condition

I've tried following solutions from Stack Overflow to resolve this issue, but I'm still unable to load external objects (Blender). Essentially, I exported it as a ThreeJS JSON file, here is the content of my JSON file: { "textures":[], ...

Is there a streamlined approach to reducing the code for an Angular Bootstrap card with a fixed length and height?

Is there a more efficient way to distribute a fixed number of cards with fixed dimensions in three rows? Currently, I am manually coding all 33 cards spread across 3 rows - 11 cards per row. Please excuse any mistakes in my code as I am still a beginner a ...

Retrieving a specific Project ID from Asana Task API using Node.js and parsing the JSON response

Utilizing the Asana Task API, we have the capability to retrieve a task's associated projects along with their GID and Notes (description text). The main objective Our aim is to extract the GID of the project containing #websiteprojecttemplate in its ...

Using the OR condition in the ternary operator within ReactJS

Recently, I have started working on a ReactJS project focusing on menus. In this project, I have successfully implemented logic for the active menu feature. For instance, when a user is on page 2, the corresponding menu item will be highlighted as active. ...

JavaScript shortening a string while joining it

I'm facing a challenge with string truncation in my laravel and JS(jquery) app. Initially, I suspected it was an issue with the backend (as indicated in my question here: Laravel Truncating Strings). However, after thorough debugging, I discovered tha ...

Tips for concealing elements beyond div boundaries

First and foremost, I want to mention that my focus is on studying frontend development, so I could really use some assistance with a task. I am looking to create a tab slider where the content on the left and right will flank it, ensuring the tab slider ...

Looking to retrieve the AssetLoadedFunc properties in the LoadAssets function? Wondering if you should use TypeScript or JavaScript

When I invoke this.AssetLoadedFunc within the function LoadAssets(callback, user_data) LoadAssets(callback, user_data) { this.glg.LoadWidgetFromURL("assets/Js/scrollbar_h.g", null, this.AssetLoaded, { name: "scrollb ...

Displaying a page with dynamic data fetched from the server-side to be utilized in the getInitialProps method of

As a newcomer to next.js, my goal for my project is to connect to a database, retrieve data, process it using express, and then utilize it on the client side of my application. I plan to establish a connection to the database within the express route han ...

A guide on using Javascript to write information to a JSON file

Let's consider an example where we have a .JSON file with the following content: [{"honda": "accord", "color": "red"},{"ford": "focus", "color": "black"}] We are looking to add another object {"nissan": "sentra", "color": "green"} into this existing ...

Can JSON.parse be used on only a portion of an object in JavaScript?

Currently, I am facing an issue with a lengthy JSON file that I am fetching from a URL using https.request. Upon attempting to parse the string with JSON.parse, I encounter an "Unexpected end of JSON input" error. It appears that there is a limit to the ...

Convert CSV into an object with additional attribute

I'm attempting to import data from a CSV file into a d3 tree graph. While I've successfully loaded the JSON version of the data, the d3.csv parser isn't returning the expected string. Some approaches I've tried include: treeData.forEa ...

Discover the final index of an array with Angular's ng-repeat functionality

I'm currently working with an Object that contains array values which I am trying to iterate over. Here's a simplified example of what I have: $scope.messages = { "1": [ { "content": "Hello" }, { "content": "How are you" }, { "conte ...

Having trouble with connect-busboy not calling the callback when using NodeJS, AngularJS, and File Upload?

Click here for the sources I am currently working on implementing a NodeJS server that allows file uploads using connect-busboy from AngularJS with the help of angular-file-upload for later analysis. The issue I'm encountering is that the callback f ...

What is the best way to present these values with spaces in between each word?

When I use console.log(JSON.stringify(selected["1"]?.others)), the output is: ["Cars","Books","Necklaces"] On the screen, however, when displaying this data, all the words appear together without spaces. It looks li ...

Is it considered ineffective to define default CSS rules?

For instance, consider a scenario where there is a table. The conventional alignment practice (whether it's an HTML specification or specific to the browsers in use) appears to be left aligning the body elements and center aligning the head elements. ...

Analyze data with diverse structures using crossfiltering technology

Exploring the world of crossfilter is a new adventure for me as I am just starting out and have limited experience with handling data. The data I am working with has a varying structure, as shown below: const data = [ {_id: 001, a: 10, b: 11, c: 12}, ...

The AJAX function is failing to return false

I found this code snippet in my index.html file: <form> <input onkeyup="firstnamecheck(this.value)" type="text" name="firstname" id="Start" class="Inputs" /> <button type="submit" name="Murad" id="tester" title="Register">Register</b ...

Exploring the power of NodeJS with nested functions for conducting in-depth search

Hey there, friends! I'm currently working on a small web application using NodeJS. One of the key features in my app is a search functionality that spans across different pages. However, I have some doubts about the nested functions related to this s ...