简体   繁体   中英

How to select elements in javascript by class name matching with multiple class names ?

I am trying to write a javascript which will select an element, which matches with either of the values"_3eAQiD" or "_2UDlNd"? The page I am using keeps on changing the class name frequently?

Presently, I am using the following code :

result.item =  getItemName("_2UDlNd"); 

I pass the class name "_2UDlNd" to a getItemName() function, where I use it as an argument to get the element by class name :

itemName = document.getElementsByClassName(item_class)[0].innerText;

However, is there any way, I can pass multiple classnames, separated by OR or in teh form of an array, to the getItemName() function, so that 'getElementsByClassName' can select the item with any of the class names which matches with the class name?

Something like this :

result.item =  getItemName("_2UDlNd" || _3eAQiD);

My problem is since the webpage keeps on changing the class name, I have to continously update the classname in the getItemName function? Any way by which I cna make the process dynamic?

Use querySelectorAll and commas:

 console.log(document.querySelectorAll('._3eAQiD , ._2UDlNd')); 
 <div class="_3eAQiD"> A </div> <div class="_2UDlNd"> B </div> 

您可以使用querySelectorAll

result.item = document.querySelectorAll("._2UDlNd,._3eAQiD")[0].innerText;

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