user3560827
user3560827

Reputation: 694

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>

Upvotes: 0

Views: 1262

Answers (4)

Surya Kavutarapu
Surya Kavutarapu

Reputation: 136

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

You can directly access default attributes like title or use getAttribute('title') instead.

Upvotes: 1

Derek Wang
Derek Wang

Reputation: 10193

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>

Upvotes: 1

Barmar
Barmar

Reputation: 780879

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>

Upvotes: 2

Kiran Dash
Kiran Dash

Reputation: 4956

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>

Upvotes: 1

Related Questions