简体   繁体   中英

How to get element by class and id name

I have a javascript code like this:

var confirmbutton = document.getElementsByClassName("btn-primary-md");
for (var y=0;y<confirmbutton.length; y++) 
  {
  confirmbutton[y].click();
//...

Im trying to make a javascript which would press a specific button with the same class and id with the below html.

<a href="" id="confirm-btn" class="btn-primary-md">Get it Now</a>

but it keeps there is another class with the same class name which keeps getting pressed:

<a href="https://example.com" class="btn-primary-md">Upgrade Now</a>

How do I get

<a href="https://example.com" class="btn-primary-md">Upgrade Now</a>

to work with my javascript?

You can get the button both by ID and class by using document.querySelectorAll :

 let confirmButtons = document.querySelectorAll("#confirm-btn.btn-primary-md"); for (let i = 0; i < confirmButtons.length; i++) { console.log("The button text is: " + confirmButtons[i].innerText); }
 <a href="" id="confirm-btn" class="btn-primary-md">Get it Now</a> <a href="https://example.com" class="btn-primary-md">Upgrade Now</a>

However, as @Andy already suggested in the comments, you better get your button by ID only (assuming your IDs are unique on the page).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM