JavaScript code for extracting information from a table

After analyzing the table below:

  <table id="cart-subtotals" cellspacing="0" class="shop_table 
  shop_table_responsive">
  <tbody>
  <tr class="cart-subtotal">
  <th>Subtotal</th>
  <td data-title="Subtotal"><span class="woocommerce-Price-amount amount">
  <span class="woocommerce-Price-currencySymbol">£</span>165</span></td>
  </tr>
  <tr class="shipping">
  <th>Shipping</th>
  <td data-title="Shipping"> Standard Delivery: <span class="woocommerce-
   Price-amount amount"><span class="woocommerce-Price-
   currencySymbol">£</span>9</span> <input type="hidden" 
   name="shipping_method[0]" data-index="0" id="shipping_method_0" 
  value="flat_rate:2" class="shipping_method"></td>
  </tr>
  <tr class="order-total">
  <th>Total</th>
  <td data-title="Total"><strong><span class="woocommerce-Price-amount 
  amount"><span class="woocommerce-Price-currencySymbol">£</span>174</span>
  </strong> <small class="includes_tax">(includes <span class="woocommerce-
  Price-amount amount"><span class="woocommerce-Price-
  currencySymbol">£</span>7.86</span> Reduced Rate, <span 
  class="woocommerce-Price-amount amount"><span class="woocommerce-Price-
  currencySymbol">£</span>1.50</span> VAT)</small></td>
  </tr>
  </tbody>
  </table>

I am seeking a method to retrieve only the number '165' (without the currency symbol) from the first column in the table.

Although my attempt failed:

function() {
  var element = document.querySelector('#cart-subtotal td:first');
  var price = element.innerHTML.match(/\d*\.\d*/)[0]; 

  return price;
}

Do you have any alternative suggestions?

Answer №1

My immediate target would be the Subtotal information attribute:

let totalAmount = document.querySelector('td[data-title="Subtotal"]');
let amountValue = totalAmount.textContent.match(/\d+/)[0]; // 205

VIEW DEMO

Answer №2

It seems like the problem lies in the method you are using to retrieve the element

(function() {
    var item = document.querySelector('.cart-subtotal td:nth-child(2)');
    var cost = item.innerHTML.match(/\d+/)[0];
    console.log(cost)
    return cost;

    })()

Give this a shot, it should do the trick

Answer №3

Give this a shot:

let price = document.getElementsByClassName("woocommerce-Price-amount amount")[0].innerHTML;
price = price.split("</span>");
price = price[1];
console.log(price); //165

Answer №4

Here is a helpful code snippet for you to try out:

function GetSpanContent() {
       var value = document.querySelector(".cart-subtotal");
        if (value !== null) {
            var spanValue = value.querySelector(".woocommerce-Price-amount");
            if (spanValue !== null && spanValue.childNodes !== null && spanValue.childNodes.length > 2)
    return spanValue.childNodes['2'].textContent.trim();
    }
}

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

Building hierarchical comments in React Native

I'm currently involved in a React Native project that includes a Nested comment section. These comments are retrieved as JSON data and displayed using a FlatList. const App = () => { const [isLoading, setLoading] = useState(true); const [data, ...

Verifying One Time Password (OTP) from MSG91 URL using ReactJS

Currently, I am working on a small project that involves receiving and verifying OTPs from MSG91. While I have managed to successfully receive OTPs using MSG91, I am encountering an issue when trying to verify OTPs - specifically, I keep getting an error ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...

New behavior in Vue 3: defineEmits is causing issues with defineProps data

Currently, I am working with Vue 3 and TS 4.4. In one of my components, I am using defineProps to define prop types. However, when I try to add defineEmits, VS Code starts indicating that my props variable is not recognized in the component template. Below ...

Creating a dynamic onclick function that depends on a variable passed from a while loop in PHP

If you're familiar with PHP, I have a scenario for you. Let's say there's a list of items generated using a while loop in PHP. Each item has a sub-list that should only appear when clicked on. I tried using the onclick function in jQuery but ...

Trigger the useEffect Hook once the condition has been satisfied

Within my component, I am utilizing the useEffect hook to monitor updates of a specific value. I have implemented a condition to prevent the useEffect function from triggering after the initial rendering. However, I noticed that each time the button is c ...

Here's a unique version: "Discovering how clients can easily connect to a new room using socketio

There are 5 rooms on my server named "A", "B", "C", "D", and "E." Server-Side In the server side code: io.on('connection', (socket) => { console.log('New user connected'); socket.on('disconnect', () => { ...

Having trouble with the sendFile function in your Node app built with Express?

Within my server.js file (where 'app' is an instance of express), I have the following code snippet. It is meant to send back a file named index.html which resides in the same directory as the server.js file. app.get('/', function (req ...

The value of a variable remains constant in an Angular controller

I am facing an issue with my HTML page that includes: <div ng-controller="MyCtrl"> <div ng-view>Some content</div> myVar: {{myVar}} </div> Along with an Angular controller: myModule.controller('MyCtrl', function($s ...

Using moment.js to perform addition of time does not yield the desired outcome

Every time I try to ---- make changes ---- var someMoment = moment('6:30 PM', ["h:mm A"]); ---- end changes ---- someMoment.add(30, 'minutes') I am not getting any desired outcome. console.log(start); -- Moment {_isAMomentObject: ...

Having trouble decoding JWE using the NPM Jose library

Although I can successfully decrypt a JWE using an older version of jose, I'm facing difficulties in utilizing the latest version API. The headers of my token are as follows: { "alg": "A128KW", "enc": "A128CBC-H ...

"Implement a feature that allows users to click on an image in a queue using

These are the images I have: <img src=img1.jpg class=pic /> <img src=img2.jpg class=pic /> <img src=img3.jpg class=pic /> <img src=img4.jpg class=pic /> <img src=img5.jpg class=pic /> <img src=img6.jpg class=pic /> .Sh ...

Shifting the MUI DataGrid Pagination table to the left with CustomPagination: A step-by-step guide

Hey everyone, I am currently diving into the MUI data grid to gain a better understanding. In order to meet my design requirements for a table view, I have incorporated the DataGrid component from MUI. For pagination, I am utilizing their custom implementa ...

Troubleshooting imagejpeg() Function Failure in PHP Server

I've been working on implementing image cropping functionality for my website. I've managed to send an array of cropped image dimensions (x, y, width, height) to my PHP script. On my localhost, the script successfully crops the image, but unfort ...

Is there a way in JavaScript to convert a web page into a string?

I'm looking for a way to retrieve the HTML content of a webpage using JavaScript, even if it's on a different domain. Similar to what wget does but in JavaScript. I intend to use this for web crawling purposes. Could anyone guide me on how to fe ...

When working with JavaScript and Node.js, it is not possible to access an object's index that is

Utilizing babyparse (PapaParse) in nodejs to convert CSV to JavaScript objects has been quite challenging for me. After processing, the output of one object looks like this: { 'ProductName': 'Nike t-shirt', ProductPrice: '14.9 ...

Can someone assist me with troubleshooting my issue of using a for loop to iterate through an array during a function call

Having recently delved into the world of Javascript, I've encountered a challenging problem that has consumed my entire day. Despite attempting to resolve it on my own, I find myself feeling quite stuck. The structure of my code is relatively simple ...

What is the best way to dynamically write a knockout data binding event using jQuery?

let $button = $('<input/>').attr({ type: 'button', value: data.styleData, id: buttonId, data - bind: event: { click: $parent.submitPopUp } }); An error is being displayed. ...

Storing the output of asynchronous promises in an array using async/await technique

I am currently working on a script to tally elements in a JSON file. However, I am encountering difficulty in saving the results of promises into an array. Below is the async function responsible for counting the elements: async function countItems(direct ...

Javascript is failing to execute promises in sequence

Currently, I am facing an issue with the execution of the code below using promises. The problem lies in the fact that the promise is not executing sequentially; it does not wait for the first block to finish before moving on to the next block. Here is th ...