简体   繁体   中英

How To Get Value Of Span Class Title Value

I would like JS to return the text value of title which is 'lost' from this line of code:

I want to print to console only the text "lost".

I tried the following (which didn't work):

 console.log(document.getElementsByClassName('_3rAzIK1XDa7ajuyjz8OJkl _12pssoQOCYKCt5amUeIK')[0].getElementsByClassName('title')[0].innerText)
 <span class="_3rAzIK1XDa7ajuyjz8OJkl _12pssoQOCYKCt5amUeIK" data-qa="text-recent-bet-status" title="lost"><i class="betgames-icon closed"></i></span>

title isn't a class name, it's an attribute. Use .getAttribute() to get its value.

 console.log(document.getElementsByClassName('_3rAzIK1XDa7ajuyjz8OJkl _12pssoQOCYKCt5amUeIK')[0].getAttribute('title'));
 <span class="_3rAzIK1XDa7ajuyjz8OJkl _12pssoQOCYKCt5amUeIK" data-qa="text-recent-bet-status" title="lost"><i class="betgames-icon closed"></i></span>

Use getAttribute() to get the value of the title attribute of selected DOM element:. Here title is an Attribute and not a class.

 console.log(document.getElementsByClassName('_3rAzIK1XDa7ajuyjz8OJkl _12pssoQOCYKCt5amUeIK')[0].getAttribute('title'))
 <span class="_3rAzIK1XDa7ajuyjz8OJkl _12pssoQOCYKCt5amUeIK" data-qa="text-recent-bet-status" title="lost"><i class="betgames-icon closed"></i></span>

document.getElementsByClassName returns the elements array based on that className .

And to get the title attribute of the selected element, you can use getAttribute function.

 console.log(document.getElementsByClassName('_3rAzIK1XDa7ajuyjz8OJkl')[0].getAttribute('title'));
 <span class="_3rAzIK1XDa7ajuyjz8OJkl _12pssoQOCYKCt5amUeIK" data-qa="text-recent-bet-status" title="lost"><i class="betgames-icon closed"></i></span>

console.log(document.getElementsByClassName('_3rAzIK1XDa7ajuyjz8OJkl _12pssoQOCYKCt5amUeIK')[0].title)

您可以直接访问标题等默认属性或使用 getAttribute('title') 代替。

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