-2

my webpage excerpt looks like this

<div class="current-timestamp" style="--duration:"00:13:19"; --absolute-position:"00:00:00";"><span class="position"></span><span class="divider"></span><span class="duration"></span></div>

i try to get the value 00:13:19 via the chrome console with this command

document.querySelector(".current-timestamp");

however i receive the full code like above.

What do i need to do to just receive "00:13:19" ?

  • 1
    I think you'd need to retrieve and parse the div's style attribute. – mykaf Oct 04 '22 at 15:20
  • Use window.getComputedStyle to access the CSS custom property. – Terry Oct 04 '22 at 15:20
  • Detailed information here: https://stackoverflow.com/questions/2664045/how-to-get-an-html-elements-style-values-in-javascript – Henning Oct 04 '22 at 15:23
  • 2
    If you want to access these data from JavaScript then add them as data attributes, they are easy to access, https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes – Oshan Abeykoon Oct 04 '22 at 15:25

1 Answers1

1

It's not common to store the value of a component in a CSS variable like you have done, however it can be accessed in the following way:

getComputedStyle(document.querySelector(".current-timestamp")).getPropertyValue("--duration");

Essentially, we are getting the computed style of the element in question, and then using getPropertyValue to get the value of the duration variable on the element.

However, I would highly advise against using CSS variables for storing non-style related values in the future.

Edit: This can actually be done using the style property directly, as this is set on the element itself:

document.querySelector(".current-timestamp").style.getPropertyValue("--duration");
Basil
  • 488
  • 1
  • 15