0

Website has a button with text that changes dynamically.

Elements before 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>

Elements after 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>

I can get the value of cost using this method:

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

This works from the online JavaScript tester at "https://jsfiddle.net/"

However on the Chrome browser the following error is returned:

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

I can confirm that the elements shown from "Elements after button text change" are present using the Developer Elements Inspector.

In the Chrome browser console I only run the following code:

var cost = document.getElementsByClassName("cost")[0].innerText;
console.log("my cost is: "+cost)
user3560827
  • 632
  • 1
  • 5
  • 22
  • *"I can confirm that the elements shown [...] are present"* - The error suggests otherwise. When you test `document.getElementsByClassName("cost")`, what does it return? Are you running this code when the page loads? Some time later? Is it on the page itself, or you're manually typing/pasting it into the console? – David Dec 09 '22 at 16:46
  • So you are trying to select the element before it exists on the page. It is like looking for a person before they walk into a room. You are not going to find them. – epascarello Dec 09 '22 at 17:07
  • I can confirm the elements that I execute the javacode multiple times while viewing the contents of the webpage button text change. – user3560827 Dec 09 '22 at 17:30

2 Answers2

0

I think you want to wait for the DOM to load

window.onload = function() {
  var cost = document.getElementsByClassName("cost")[0].innerText;
  console.log("my cost is: "+cost);
}
  • I execute the javacode multiple times while viewing the contents of the webpage button text change and still get the same, the loading should have completed if I can view the changes live on the webpage correct? – user3560827 Dec 09 '22 at 17:30
0

Just wait for the document to load. above solution could be workable or try this, it's gonna work.

<script>
    var cost = document.getElementsByClassName("cost")[0]?.innerText;
    console.log("my cost is: "+cost)
</script>
Asim Imam
  • 313
  • 1
  • 3
  • 12