Unable to click the specific ID I need to click the button with javascript

Hi all

I have done a lot of searching and got a bit confused with everything, hence reaching out for some help.

I have a button that I need to select, but due to the way that its been coded, I needed to make some Javascript to click the button which is this and it works well.

Whilst this works great, its just selecting the first ID which is normally 1 and I want to be able to select either 2 o 3 and if thats not available 1 but I dont have a clue and I have tried various js things found, but it doesnt work. So someone please help me before I lose the will to live :wink:

Hi em, can you take a look at this? Thanks em!

@lisa.s You are using a CSS class-based selector to find the element so you are not able to distinguish between a list of elements that share that class. The solution is to use the id, instead.

document.querySelector("a.btn#1").click()
document.querySelector("a.btn#2").click()
document.querySelector("a.btn#3").click()
1 Like

thanks Russ, I tried with your method, but I couldnt get it to work but our website is so old and I whinged so loudly (im in the office today) that someone took pity on me and wrote me this: ‘var buttons = document.querySelectorAll(“a.selectDeparture”); var num; if(buttons.length === 1){ num = 0; } else { num = 1 }; buttons.item(num).click();’
Which works exactly as I wanted it to.

However, I did learn something new from you today about CSS (I googled and read a bit more than I would have normally) so thanks again for your time :slight_smile:

1 Like