+ 5

How to add multiple ids to a getElement by Id

how would i make it so it is for example posx = document.getElementById("right_div, left_div").offsetLeft; posy = document.getElementById("right_div, left_div").offsetTop; Instead of just posx = document.getElementById("right_div, left_div").offsetLeft; posy = document.getElementById("right_div, left_div").offsetTop; I looked online but all the stuff on stack overflow is kinda confusing for a noob like me😂

13th Feb 2018, 2:44 PM
Ole113
Ole113 - avatar
4 odpowiedzi
+ 3
First, You can't give multiple parameters to document.getElementById() Second, you can use document.getElementsByClassName() by replacing id's with class Example- let you have 3 elements with class='left_div', you can use var left_div = document.getElementsByClassName('left_div'); this creates an array of elements with class 'left_div'. Now, it's your turn!
13th Feb 2018, 3:01 PM
777
777 - avatar
+ 4
A smart solution would be to use document.querySelectorAll() instead of document.getElementById(): it takes only one parameter (string) also, but you could specify multiple selectors separated by coma (as you can do for css rules declaration): var elementsArray = document.querySelectorAll("#right_div, #left_div"); ... and then iterate over the elements array-like (as getElementsByClassName() or getElementsByTagName(), all are returning an array-like structure, not a real array: all available methods on arrays are not available on those special lists) and access them by indexes (in square brackets). Be careful that order of selected elements should not reflect order of selector parameter, but rather order of elements in the document source code ;) (and it's safer to consider there's no predictable order at all). However, you cannot assign multiple values to a simple variable, such as: posx = elementsArray.offsetLeft; ... as you have many elements selected, so you also get differents values for attributes of each ^^ But you could do: var posx = []; // create an empty array; var posy = []; // create another empty array; for (var i = 0; i < elementsArray.length; i++) { posx[i] = elementsArray[i].offsetLeft; posy[i] = elementsArray[i].offsetTop; }
13th Feb 2018, 6:56 PM
visph
visph - avatar
+ 3
you cannot use one single getElementById() method to get more than one element by id.If you know the elements are similar just assign them to a single class and get the class once.The system will automatically parse all elements into an array
13th Feb 2018, 2:56 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 1
Thanks @Blue and @Brains
13th Feb 2018, 4:25 PM
Ole113
Ole113 - avatar