The JavaScript value of the button text once it has been modified

We have a website feature where the button text changes dynamically.

Here are the elements before the button text change:

<button _ngcontent-wex-c70="" 
    class="btn btn-wait buy font-family-title height-70 pp-sun-ins"><label _ngcontent-wex-c70="" translate="" 
    class="font-family-title label">BUY</label>
</button>

And here are the elements after the button text change:

<button _ngcontent-wex-c70="" 
    class="btn btn-root press font-family-title pp-sun-ins"><span _ngcontent-wex-c70="" 
    class="d-power power-column justify-content-center align-items-center"><label _ngcontent-wex-c70="" translate="">EXIT NOW</label><label _ngcontent-wex-c70="" 
    class="price"><span _ngcontent-wex-c70="" 
    class="cost">1.46</span><i _ngcontent-wex-c70="" 
    class="UNT"></i></label></span>
</button>

To extract the value of the cost, I use this method:

<script>
    var cost = document.getElementsByClassName("cost")[0].innerText;
    console.log("The cost is: "+cost)
</script>

This method works fine on the online JavaScript tester found at "https://jsfiddle.net/"

However, when using the Chrome browser, I encounter the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'innertext')

I have verified that the elements mentioned in "Elements after button text change" are indeed present using the Developer Elements Inspector.

In the Chrome browser console, I only execute the following code:

var cost = document.getElementsByClassName("cost")[0].innerText;
console.log("The cost is: "+cost)

Answer №1

It's best to ensure the DOM is fully loaded before executing any scripts.

document.addEventListener('DOMContentLoaded', function() {
  var price = document.querySelector('.price').innerText;
  console.log('The price is: ' + price);
});

Answer №2

Be patient while the file is loading. The proposed solution might be effective, or you can give this alternative a shot.

<script>
    var price = document.getElementsByClassName("price")[0]?.innerText;
    console.log("The price is: "+price)
</script>

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

Error: Unable to access the property 'fn' of an undefined object in electron version 2 using Angular 6

I am currently utilizing Angular 6.0.3 and electronjs 2.0.2 with the package.json configuration shown below: { "name": "test", "version": "1.0.0", "license": "MIT", "main": "electron-main.js", "author": { "name": "Moh ...

In what specific format does this plugin expect the callback string to be encoded as? (jquery-ui-multisearch)

Currently, I'm working with a plugin named "Jquery-ui-multisearch" that provides an autocompletion feature in an input field based on either a provided array or an external source (such as ajax/api, etc). You can find more information about this plugi ...

What is the process of implementing a service in AngularJS?

For my Angular JS project, I am working on creating a module to include my service (file: utils/productos.js) and then load it as a dependency for my ventas module (ventas/ventas.js). However, I encountered the following error: Error: [$injector:nomod] Mo ...

Solution to trigger CSS :hover to refresh following a transition (such as expanding a menu)

While there are existing discussions on this topic, I am presenting my query for two specific reasons: It introduces a potential alternative solution The demo code could be helpful to individuals looking to emulate a menu Following a CSS transition, the ...

Passing events from Swift or Objective-C to JavaScript is a seamless process

A custom class was created with the following condensed version provided. For a reference to the full file, please visit this link. @objc(NativeMethods) class NativeMethods: RCTEventEmitter { @objc(sendEventToJSFromJS) func sendEventToJSFromJS { s ...

JavaScript/Typescript is throwing an error because it is unable to access the property 'username' of an undefined object

In my project, I am attempting to compile a list of Profile objects and then extract specific elements from each object in the list. To accomplish this, I have defined a public interface named Profile, imported it into my component, and instantiated a new ...

Using JavaScript and HTML to show the current month, date, and year on a webpage

I am looking to display not only the time, but also the month, date and year. My attempted solution involved creating variables for the month, day and year, and then using getElementById. Here is an example of what I tried: var d = date.getDay(); var mn ...

Modify the Div background color by accessing the HEX value saved in a JSON file

(I made a change to my code and removed the br tag from info2) Currently, I have successfully implemented a feature using jQuery that reads color names and hex values from a JSON file, populates them in a drop-down select menu (which is working fine). Now ...

Struggling to make dynamically created SVG 'use' elements function properly

SVG offers a unique system with symbol and use where icons can be defined once and reused throughout the SVG using use. However, I am having trouble getting it to work from JavaScript. You can view an example on this JSFiddle link. When programmatically ...

The issue of Ejs partial header and footer file only functioning in one file and not the other (both at the same directory level)

I'm in the process of setting up a view page for a post on the main page of a website. Both pages share the same header and footer files, located at the same directory level. However, while one page is functioning correctly, the other is not. The erro ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

"Notification: The marker element has been eliminated" encountered while attempting to restore text ranges using Rangy within a Vue component

I have a rather intricate Vue component that includes a contenteditable div. My goal is to highlight words within this div using the Rangy library and add extra markup while retaining this markup even after editing the text. Initially, I planned on asking ...

Enhance your website with the jQuery autocomplete feature, complete with

Is there a way to incorporate smaller text descriptions alongside the search results displayed on my website? The descriptions are available in the data array used by autocomplete and can be accessed using the .result function by calling item.description. ...

Developing an npm package for storing a communal instance

I am interested in developing an npm library that can be initialized with a specific set of keys and then utilized throughout an entire project. Here is an illustration of how I envision its usage: In the main component or page import customLib from &quo ...

Retrieve the information in a div element from an external website by utilizing AJAX

Exploring the world of AJAX is new to me, and I am eager to fetch content from a div on an external site and display it on my own website. Below is the current code snippet I have: <html> <head> <script src="https://ajax.googleapis.com ...

What causes the variable to be invisible in the imported file?

Within the main.js file, there is a specific code snippet: var test_mysql = require('./test_mysql.js') ... //additional code before(function(){ test_mysql.preparingDB(test_mysql.SQL_query.clear_data); // or test_mysql.preparingDB(SQL ...

Serialize a form while keeping the submitted data private

Is there a way to achieve serialization without triggering the submit function for an ajax call? I've searched extensively for a solution to this issue without any luck. The java script function is invoked when a button within the form is clicked. do ...

Click on the child element while it is already being clicked by manually implementing the 'declick' function in Javascript

Hey there, I'm looking for suggestions on a better title for this issue. I couldn't come up with the right wording myself. Problem I currently have a Google Maps element with pointer events set to none, preventing it from being scrolled when ho ...

Customize the background color of MaterialUI KeyboardDateTimePicker without altering the padding and layout of the component

Is it possible to alter the background color of KeyboardDateTimePicker components without affecting the padding and layout? I attempted to set the background property to style={{background: "rgb(232, 241, 250)"}}, but when combined with inputVari ...

The logout feature might refresh the page, yet the user remains logged in

Currently, I am enrolled in a course on Udemy where the instructor is utilizing Angular 2. My task involves building the app using the latest version of Angular. The issue that I am facing pertains to the logout functionality. After successfully logging ou ...