0

getElementById(id) returns the element with the matching ID attribute. How can I get the last occurrence of this element, as opposed to the first?

<!DOCTYPE html>
<html>
<body>

<button onclick="getLast()">Click me</button>

<div id="username">Lisa</div>
<div id="username">Chris</div>

<script>
function getLast() {
    alert(document.getElementById("username").innerHTML);
}
</script>

</body>
</html> 
livin_amuk
  • 1,285
  • 12
  • 26

4 Answers4

4

id is always unique. No two DOM elements can have the same id. In your case use the class attribute. Use getElementsByClassName which will return a collection. Get its length and use that value to get the last element.

function getLast() {
  var getLastElemIndex = document.getElementsByClassName("username").length - 1;
  console.log(getLastElemIndex)
  alert(document.getElementsByClassName("username")[getLastElemIndex].innerHTML);
}
<div class="username">Lisa</div>
<div class="username">Chris</div>
<button onclick="getLast()">Click me</button>
brk
  • 48,835
  • 10
  • 56
  • 78
3

id should be unique. But we don't have control on how people write their code and I also meet this case sometimes: "I need to parse the page and they are using same id"

You can treat id as an attribute and use querySelectorAll:

<button onclick="getLast()">Click me</button>
<div id="username">Lisa</div>
<div id="username">Chris</div>
<script>
function getLast() {
    tags = document.querySelectorAll('[id="username"]');
    alert(tags[tags.length - 1].innerHTML);
}
</script>

And the best practice should be using class.

CtheSky
  • 2,484
  • 14
  • 16
1

The id of a HTML element is meant to be unique. You should specify the class instead:

<div class="username">Lisa</div>
<div class="username">Chris</div>

Then use Document.getElementsByClassName() to get all elements of that class:

var usernames = document.getElementsByClassName("username");

Alternatively, you can use Document.querySelectorAll():

var usernames = document.querySelectorAll(".username");

And then you can get the last one:

var lastUsername = usernames[usernames.length - 1];
Luke Horvat
  • 337
  • 1
  • 9
1

Even you can do it by tag name div, as @brk said id must be unique.

function getLast(){
  var divs = document.querySelectorAll("div");
  console.log(divs[divs.length - 1].textContent);
}
getLast();
<button onclick="getLast()">Click me</button>
<div>Lisa</div>
<div>Chris</div>
GRESPL Nagpur
  • 2,048
  • 3
  • 20
  • 40