Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure JS equivalent of Jquery eq()

What is the pure equivalent of jquery's eq(). For example, how may I achieve

$(".class1.class2").eq(0).text(1254);

in pure javascript?

like image 977
Kamran Ahmed Avatar asked Sep 21 '13 09:09

Kamran Ahmed


2 Answers

To get the element index in the array you can use [] in javascript. So to reproduce your code you can use this:

document.querySelectorAll('.class1.class2')[0].textContent = 1254;

or

document.querySelectorAll('.class1.class2')[0].innerHTML = 1254;
  • In your example 1254 is a number, if you have a string you should use = 'string'; with quotes.
  • If you are only looking for one/the first element you can use just .querySelector() insteal of .querySelectorAll().

Demo here

More reading:

MDN: textContent
MDN: innerHTML
MDN: querySelectorAll

like image 149
Sergio Avatar answered Sep 29 '22 20:09

Sergio


querySelectorAll returns an array, so you can get the element 0 using index

document.querySelectorAll(".class1.class2")[0].innerHTML = 1254
like image 29
Arun P Johny Avatar answered Sep 29 '22 20:09

Arun P Johny