1

I am a newbie in JavaScript and I currently have a script that presses a button for me. I tried it on one website and it worked great. Now I did the exact same thing on another website and it wouldn't work. The differences I could spot in HTML were that when I hovered over it with the element selector, one button had was formatted as button#id.class and the other one was just button.class. The two are also have some different attributes, but I think most of them are just website dependent.

So here is the HTML of the first button:

<button id="id" class="classname" type="button">Button</button>

Here is the HTML of the second button, I removed the svg data since I don't think it's necessary, I can add it later if you need it:

<button class="classname" aria-label="aria label" title="title"><svg></svg></button>

Here is the line of JavaScript that actually presses the button, at least the second one:

document.getElementsByClassName('classname')[0].click()
gurkensaas
  • 793
  • 1
  • 5
  • 29
  • 1
    Are you asking [What is the difference between id and class in CSS, and when should I use them?](/q/12889362/4642212) (and [What's the difference between an id and a class?](/q/544010/4642212))? – Sebastian Simon Jun 12 '21 at 19:30
  • @SebastianSimon As I stated at the beginning, I am a complete newbie to JavaScript. I could be asking this, I can't be sure though. – gurkensaas Jun 12 '21 at 19:35

1 Answers1

1

A . before a string in a selector indicates a class. So .class will select an element with the class of class.

A # before a string in a selector indicates an ID. So #foo will select an element with the ID of foo.

So

button#id.class

means nearly the same thing as

button.class

except that the first also has an ID of id.

Because IDs should be unique, this

button#id.class

should also be equivalent to just

#id
document.getElementsByClassName('classname')[0].click()

If you only need a single element, use querySelector instead - no need to retrieve the whole collection.

document.querySelector('.classname').click();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • or `document.querySelectorAll('.classname')[0].click()` – mplungjan Jun 12 '21 at 19:34
  • If there is a space in the classname, should I leave it or add a `.` – gurkensaas Jun 12 '21 at 19:38
  • @gurkensaas A space in a selector means something completely different - it's the descendant selector. Eg `#foo .bar` will select the child here: `
    `. A space in the class name indicates multiple classes, so the most precise way to do it would be to list both, eg `` with `span.foo.bar.`
    – CertainPerformance Jun 12 '21 at 19:40
  • Your answer didn't exactly solve my problem but it pointed me in the right direction. I used `document.getElementById('Id').click();` and it worked great. – gurkensaas Jun 12 '21 at 19:46