0

Im trying to select a child div from an array with the variable x

This is only a sketch to illustrate what I'm trying to do:

var x= 0;
 trackN = document.querySelector( .track :nth-child(x))


But querySelector doesn't accept variables.

I don't have ids on these objects (i could add them if this is the only option) nor jquery...

3
  • I don't really understand what you're trying to do. Do you want to get the parent element of the elements querySelectorAll? This answer covers that stackoverflow.com/questions/6856871/…
    – Wryte
    Commented Apr 1 at 1:58
  • you want var parentDiv = tracks[x] Commented Apr 1 at 1:59
  • @Wryte No, I have multiple child elements and all have the same id. I want a variable that changes on a button click and thus changes what child gets displayed.
    – Dr_ Buhu
    Commented Apr 1 at 2:08

1 Answer 1

1

querySelector() accepts a string so you should be able to pass a variable...

document.querySelector('.track :nth-child('+x+')');
5
  • Oh really? May have been a mistake on selecting the right child then? Why have y written + x + btw?
    – Dr_ Buhu
    Commented Apr 1 at 2:49
  • x is a number... your variable! Its value will join up with the rest of the string.
    – passThru
    Commented Apr 1 at 2:51
  • Oh! So this was just a styling problem then. Thank you!
    – Dr_ Buhu
    Commented Apr 1 at 2:53
  • Fare thee well…
    – passThru
    Commented Apr 1 at 2:54
  • Fare ther well!
    – Dr_ Buhu
    Commented Apr 23 at 14:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.