8

I have several <select> elements in my page. Is there any easy way to select the last one of them? This brings me the first one:

document.getElementById("myList")

UPDATE:

Sorry for the wrong usage of getElementById. Let me change my question: How to access the last one of a certain element using getElementsByTagName?

document.getElementsByTagName("select")

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Ned
  • 1,055
  • 9
  • 34
  • 58
  • 1
    There should only be one element with the id `mylist`... – brso05 Nov 13 '15 at 15:43
  • 1
    The id of an element has to be unique, you must not have more then one element with the id `myList`. Use e.g. _class_ instead [Document.getElementsByClassName()](https://developer.mozilla.org/en/docs/Web/API/Document/getElementsByClassName). – t.niese Nov 13 '15 at 15:43
  • document.getElementsByTagName would be better for you. – Marcus Abrahão Nov 13 '15 at 15:44
  • Possible duplicate of [JavaScript and getElementById for multiple elements with the same ID](http://stackoverflow.com/questions/3607291/javascript-and-getelementbyid-for-multiple-elements-with-the-same-id) – t.niese Nov 13 '15 at 15:46
  • Sorry for wrong usage of getElementById. Let me change my question: How to access the last one of a certain element using getElementsByTagName? Ex. document.getElementsByTagName("select") – Ned Nov 13 '15 at 16:32
  • [Marcus Abrahão](http://stackoverflow.com/a/33696531/1960455) already answered how to get the last element. – t.niese Nov 13 '15 at 17:10

3 Answers3

12
var allSelects = document.getElementsByTagName("select");
var lastSelect = allSelects[allSelects.length-1];
Ned
  • 1,055
  • 9
  • 34
  • 58
5

You shouldn't be using more than one element with the same Id. A better option is document.getElementsByTagName i. e. document.getElementsByTagName("input")[document.getElementsByTagName("input").length - 1]

Marcus Abrahão
  • 696
  • 1
  • 8
  • 18
5

A more elegant solution:

document.querySelector("select:last-child")
overallduka
  • 1,520
  • 19
  • 27