简体   繁体   English

如何使用没有 id 的 Javascript 访问元素?

[英]How to access elements using Javascript with no id?

I'm trying to access an element that has no id and has a shared classname, using Javascript.我正在尝试使用 Javascript 访问没有 id 且具有共享类名的元素。 How can I successfully do that?我怎样才能成功做到这一点?

I tried using document.getElementsbyClassName property, but since the classname is shared by other elements, this is not working.我尝试使用document.getElementsbyClassName属性,但由于其他元素共享类名,因此这不起作用。

   <a class="sharedClass anotherClass" href="www.mybooks.com" data-m="{"CN":"uniquename"}"> Proceed </a>

I want to be able to click the Proceed element from the above code.我希望能够从上面的代码中单击Proceed元素。 Please note that uniquename is unique to this element.请注意, uniquename对该元素是唯一的。 I'm thinking we can use that somehow here but am not really sure.我想我们可以在这里以某种方式使用它,但我不确定。

As @Buffalo alluded to in his comment, you could get a list of all elements sharing the class name and loop over the result set and check the data-m attribute until you find the one you want:正如@Buffalo 在他的评论中提到的那样,您可以获得共享类名的所有元素的列表,并循环遍历结果集并检查data-m属性,直到找到您想要的元素:

 var elements = document.getElementsByClassName("sharedClass"); var myElement; for (var i = 0; i < elements.length; i++) { if (elements[i].getAttribute("data-m") == '{"CN":"uniquename"}') { myElement = elements[i]; } } console.log(myElement);
 <a class="sharedClass anotherClass" href="www.mybooks.com" data-m='{"CN":"uniquename"}'> Proceed </a> <a class="sharedClass anotherClass" href="www.mybooks.com" data-m='{"CN":"uniquename2"}'> Proceed </a>

You can also be a bit more succinct by leveraging querySelector instead:你也可以通过使用querySelector来更简洁:

 var myElement = document.querySelector("[data-m='{\\"CN\\":\\"uniquename\\"}"); console.log(myElement);
 <a class="sharedClass anotherClass" href="www.mybooks.com" data-m='{"CN":"uniquename"}'> Proceed </a> <a class="sharedClass anotherClass" href="www.mybooks.com" data-m='{"CN":"uniquename2"}'> Proceed </a>

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

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