最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom - How to select the last one of a certain element in JavaScript - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question edited Nov 17, 2015 at 21:47 Mr Lister 46.6k15 gold badges113 silver badges155 bronze badges asked Nov 13, 2015 at 15:42 NedNed 1,20710 gold badges37 silver badges62 bronze badges 6
  • 1 There should only be one element with the id mylist... – brso05 Commented Nov 13, 2015 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(). – t.niese Commented Nov 13, 2015 at 15:43
  • document.getElementsByTagName would be better for you. – Marcus Abrahão Commented Nov 13, 2015 at 15:44
  • Possible duplicate of JavaScript and getElementById for multiple elements with the same ID – t.niese Commented Nov 13, 2015 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 Commented Nov 13, 2015 at 16:32
 |  Show 1 more comment

3 Answers 3

Reset to default 12
var allSelects = document.getElementsByTagName("select");
var lastSelect = allSelects[allSelects.length-1];

A more elegant solution:

document.querySelector("select:last-child")

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]

发布评论

评论列表(0)

  1. 暂无评论