简体   繁体   中英

How to get a JS value from an HTML element?

I've got a variable called grabber that gets a class and I need to be able to compare the values of all the classes it grabs.

var grabber = document.getElementsByClassName("compareDiv");

It will return (5024)Votes or however many votes are listed on the div. I need to be able to compare them but from what I understand I would need to somehow make it an integer or omit certain characters so it can compare the value of the numbers? Any help is greatly appreciated!

Iterate over elements, get their textContent and use parseInt() (or parseFloat() if values were fractional) to convert the value to a number:

var elements = document.getElementsByClassName('compareDiv'),
    count    = elements.length,
    numbers  = [];

for (var i = 0; i < count; i++) {
    numbers.push(parseInt(elements[i].textContent));
}

// The `numbers` array contains your numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM