Search code examples
javascriptgreasemonkey

How to search element by class and retreive title attribute in Javascript (greasemonkey)


I'd like to select this element:

<span class="score likes" title="22">22 points</span>

such as: var likes = comment.getElementsByTagName('score likes').title;

and then return the value of "title" tag.

I've found lots of posts on how to select element by class or title, but I haven't been able to find how to select element by class and then get the value of title to save to a variable. This is for a grease-monkey script.

Edit: This is NOT a duplicate question, does anyone ever read the question before flagging for duplicate questions? To be extra clear, I do NOT want to search by the TITLE tag, I want to GET the value of the title tag and save it to a variable. I do not know what the value of the title tag is before searching.


Solution

  • Taking some liberties for your original selection method (getElementsByTagName => querySelector) , you can access your element's attributes using getAttribute():

    var likes = comment.querySelector('.score.likes').getAttribute('title');