I was hoping someone could help me with some javascript that would click on this button:
<div tabindex="0" role="button" id="id_72229384732282" class="collapsed focus-visible" data-tutorial-selector-id="filterButton" aria-label="Filter rows">
I can’t use the id_7222…. because this is dynamic and changes after a page refresh. Is there a way to click this button based on the id="filterButton"?
Thanks!
I’ve tried all sorts of methods but I know my syntax or the class reference is wrong. Here are the general ones I’ve tried:
document.getElementsByClassName('filterButton').click();
document.getElementById("filterButton");
2
Answers
Notice the
s
in getElements
ByClassName? That means it is plural and returns a collection. You would need to index your way to the button, so it would bedocument.getElementsByClassName('focus-visible')[0].click()
– because you cannot use getElementsByClassName to get at a data attributeInstead you can use
which will click the FIRST element with that attribute and value
If you have more than one element with the attribute
data-tutorial-selector-id="filterButton"
, then you need to be more specific.will click the first DIV with that attribute and
will click the SECOND div with that attribute (the collection returned by querySelectorAll is 0 based)
If the id is dynamic and you can’t use it, you can use class to select the element.
Your html element has
collapsed focus-visible
class.If you don’t want to use it, and rather use filterButton, you should edit your html and add filterButton to classes.
(currently on your html, ‘filterButton’ is not defined among classes. )
then you can select it on JavaScript
IF you can’t touch/ edit your html, then you should select your element like this, (as @mplungjan also points out‘)
SideNote:
data-tutorial-selector-id="filterButton"
is a ‘data’ attribute.more info.
It is used to store data on html and can be retrieved in JavaScript side using keyword
dataset
On CSS side, you can use this data attribute as a selector