简体   繁体   中英

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. 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.

   <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. Please note that uniquename is unique to this element. 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:

 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:

 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>

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