简体   繁体   中英

How can I get the value of an attribute inside a <span> element?

I'm trying to extract a game score from the console for a JS game.

document.getElementById("game").getElementsByClassName("game-score")

This returns the span which contains the score, which is:

<span class="game-score" score="550"></span>

I'm trying to extract the score element, so I want just the 550 returned. Is there an easy way to do this?

Use getAttribute()

document.getElementById("game").getElementsByClassName("game-score")[0].getAttribute("score")

 console.log(document.getElementById("game").getElementsByClassName("game-score")[0].getAttribute("score")) 
 <div id="game"> <span class="game-score" score="550"></span> </div> 

Yes, add [0].getAttribute("score"); to the end of your existing chain.

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