简体   繁体   English

如何通过class和id名称获取元素

[英]How to get element by class and id name

I have a javascript code like this:我有这样的 javascript 代码:

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.我正在尝试制作一个 javascript,它将按下具有相同 class 和 id 的特定按钮,具有以下 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:但它仍然有另一个 class 具有相同的 class 名称,它不断被按下:

<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?与我的 javascript 一起工作?

You can get the button both by ID and class by using document.querySelectorAll :您可以使用document.querySelectorAll通过 ID 和 class 获取按钮:

 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).但是,正如@Andy 已经在评论中建议的那样,您最好仅通过 ID 获取按钮(假设您的 ID 在页面上是唯一的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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