Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the last one of a certain element in JavaScript

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")

like image 891
Ned Avatar asked Nov 13 '15 15:11

Ned


3 Answers

var allSelects = document.getElementsByTagName("select");
var lastSelect = allSelects[allSelects.length-1];
like image 85
Ned Avatar answered Oct 20 '22 17:10

Ned


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]

like image 23
Marcus Abrahão Avatar answered Oct 20 '22 17:10

Marcus Abrahão


A more elegant solution:

document.querySelector("select:last-child")
like image 24
overallduka Avatar answered Oct 20 '22 17:10

overallduka