How to assign html attributes dynamically?

I am trying to do this:

let arr = document.getElementsByClassName("CardSet0");

 		for (  i=0; i < arr.length; i++) 
 	    	cardInstance0_Arr[i] =   arr[i]; 	
 	    	var e = cardInstance0_Arr[i].element(); 
 	    	 e.dataset.key0 = "abcd" ;
 	    	 //////e.dataset.["data-key0"] = "abcd";  	    		

but I get undefined in return. What is the right way?

Remove .element()… in Vanilla-JS document.getElementsByClassName already returns a list of elements.

You could also use document.querySelectorAll like this…

let arr =  document.querySelectorAll (".CardSet0");
1 Like

Here is also an performance comparison for high performance scenarios. Mostly I personally use querySelectors because the allow complex queries. For render intensive stuff (recurring calls, high volume loops etc.) you should switch to the more dedicated commands.