1. Understanding The Markup
Head on over to YouTube and open your favourite video. Pause the video and press Ctrl+Shift+I on your keyboard to fire up the Dev Tools! We will be using Google Chrome, but feel free to follow along using any browser of your choice.
The next step is to press Ctrl+Shift+C on your keyboard, which will enable you to select an element by clicking on it. Chrome will automatically show its HTML in the DOM, without you requiring to search for it. Go ahead and click on the Like button. Don’t worry, this won’t trigger the button, but only highlight the button’s HTML for you.
As you can see in the image above, Chrome has highlighted the <yt-icon> tag instead of the actual <button> tag. This is because the only thing contained by the button is its icon, that we click on.
Therefore, all we need to do is select the appropriate <button> tag and call the click() method on it!
2. Selecting The Element – Part 1
You will need to observe the DOM a little more to understand why. Press Ctrl+Shift+C again and click on the Dislike button this time. Observe that both the Like and Dislike buttons have the same id and class properties, that is “style-scope it-icon-button”. This will make it problematic for us to get the element by using id or class.
Do know, that using getElementsByClassName(‘style-scope yt-icon-button’) will return all the elements with this class. We could have just selected the button from the list of elements returned, but that would be a clumsy way to do it.
Digging around the DOM like a detective, I found that the aria-label attribute of the Like button contains the “like” keyword, while the same attribute of the Dislike button contains the “dislike” keyword. Voila! 😎
3. Selecting The Element – Part 2
So how can we select an element in JS by a string contained in the value of an attribute of our choice? Answer: querySelector()
Switch to the Console tab in Dev Tools and run the following code:
Hurray! We get the element!
But how did this work? Let’s break it down.
Using the querySelector method, we can grab an element by its attribute name. The syntax is:
document.querySelector('[attr]'); // attr is the attribute name
Similarly, if we need to select an element by the value of one of its attributes, we can use:
document.querySelector('[attr=value]'); // value is the attribute value
Finally, if we need to select an element by an attribute whose value is contained by a certain value, we can use:
document.querySelector('[attr~="value"]'); // the tilde symbol accomplishes this
4. Programmatically Clicking The Button
Thus we get the final script:
Did you enjoy this article? If so, share it with your friends! 😎