Recuvan Recuvan - 1 year ago 65
Javascript Question

How to find a value of an attribute of an element

Here is a piece of code

<span class="balance themecolor" data-balance="2800">

I'm looking for a way to extract the value of data-balance and set it as variable x, but I have absolutely no idea how to do it. I know of the existence of .val() but I don't know if I can apply it to this code. I'm looking a for a one line long solution.

Answer Source

If you're using jQuery (as you've mentioned .val()):

var x = $("[data-balance]").attr("data-balance");

Or if you aren't:

var x = document.querySelector("[data-balance]").getAttribute("data-balance");

In both cases, the [data-balance] is a CSS selector for the element; adjust as needed. For instance, with that element, and assuming no other elements with either of its classes, you could use .balance, .themecolor, or even .balance.themecolor.

jQuery will find all elements matching the selector (you can change that if it's an issue, usually it isn't), but then only give you the attribute value for the first one.

querySelector will stop with the first one. If you want to find them all and get a list, use querySelectorAll (and then index into it to get the individual ones).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download