Jeff Arries Jeff Arries - 20 days ago 6
CSS Question

Can you use variables in getElementsByClassName("")[]? And how?

I'm trying to to make the class number selector on

document.getElementsByClassName("photo")[2].setAttribute("id", "current_page");
, i.e. the
2
be a variable.

Here's my real code:
HTML:
onclick="test(this)"


And JS:


function test(y) {
var x = y;
document.getElementsByClassName("photo")[2].setAttribute("id", "current_page");
}





So how can I make the class selector (on example it is
[2]
), a variable?

Thanks so much!

Answer

if add the attribute id at the same element. use like that

function test(that) {
	
	that.setAttribute("id", "current_page");
}

Comments