-1

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!

Emmet Arries
  • 539
  • 2
  • 12
  • 35

2 Answers2

2

Not sure I understand your requirement from your example, but you can use a variable for the class name:

var className = 'photo';    
var elements = document.getElementsByClassName(className);

Although from your example you seem to want the third element returned by getElementsByClassName? To select the nth element, again using a variable, you can do:

var elementIndex = 2;
var element = document.getElementsByClassName(className)[elementIndex];

Hope I've understood, but add a comment if this isn't what you're trying to get.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Mark Williams
  • 2,268
  • 1
  • 11
  • 14
1

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

function test(that) {
 
 that.setAttribute("id", "current_page");
}
prasanth
  • 22,145
  • 4
  • 29
  • 53