user9375528
user9375528

Reputation:

Getting the last class name in plain js

I can't seem to find a post related to this topic on here or on other websites that is not jQuery based. I need a plain JavaScript solution to do what I need to do.

OK so I need to get the last class name element without using something like this

document.querySelectorAll('.name')[7].innerHTML;

I need a method that don't require me counting and selecting the last class name by the count number between the square brackets like the example above. The reason why is let's just say I

have 100s of elements on the page with the class name call name I wouldn't want use the above example structure for that situation.

My code where I'm stuck at

//????? I will like the last class name to be outputted in a alert but how?
/*alert(last_class_name);*/
  <h1 class='name'>Adam</h1>
  <h1 class='name'>Bob</h1>
  <h1 class='name'>Cindy</h1>
  <h1 class='name'>Danny</h1>
  <h1 class='name'>Eddy</h1>
  <h1 class='name'>Frank</h1>
  <h1 class='name'>George</h1>
  <h1 class='name'>Henry</h1>

NOTE:

Problem solved look at my answer and Alexander Nied's answer to better understand the answer.

Upvotes: 1

Views: 910

Answers (2)

Jhecht
Jhecht

Reputation: 4435

The following code uses a trick because what is returned by document.querySelectorAll() is a NodeList, and does not have the normal functions of an array such as .pop().

This trick converts the NodeList into an Array so that you can call .pop()

The other way to do so is the same way that Alexander Nied has commented just before I managed to finish this answer.

let arr = [].slice.apply(document.querySelectorAll('.name'));
let lastEl = arr.pop();
console.log(lastEl.innerHTML);
<h1 class='name'>Adam</h1>
<h1 class='name'>Bob</h1>
<h1 class='name'>Cindy</h1>
<h1 class='name'>Danny</h1>
<h1 class='name'>Eddy</h1>
<h1 class='name'>Frank</h1>
<h1 class='name'>George</h1>
<h1 class='name'>Henry</h1>

Edit

Alexander has reminded me of the Spread Operator in ES6, which can turn this code into

let arr = [...document.querySelectorAll('.name')];
let lastEl = arr.pop();
console.log(lastEl.innerHTML)
<h1 class='name'>Adam</h1>
<h1 class='name'>Bob</h1>
<h1 class='name'>Cindy</h1>
<h1 class='name'>Danny</h1>
<h1 class='name'>Eddy</h1>
<h1 class='name'>Frank</h1>
<h1 class='name'>George</h1>
<h1 class='name'>Henry</h1>

Upvotes: 2

Alexander Nied
Alexander Nied

Reputation: 13623

You could grab the names in one query then simply grab by index of the total length minus 1, as seen below:

let names = document.querySelectorAll('.name');
let last = names[names.length-1];
console.log(last);
  <h1 class='name'>Adam</h1>
  <h1 class='name'>Bob</h1>
  <h1 class='name'>Cindy</h1>
  <h1 class='name'>Danny</h1>
  <h1 class='name'>Eddy</h1>
  <h1 class='name'>Frank</h1>
  <h1 class='name'>George</h1>
  <h1 class='name'>Henry</h1>

Upvotes: 6

Related Questions