Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementsByClassName vs. jquery

If my original function was:

document.getElementsByClassName('blah')[9].innerHTML = 'blah';

...how would I change that so I get that same item in jquery? I have this, but when I put '[9]' at the end it doesnt work:

$(data).find('.blah')[9].html();

It I leave the [9] out, it only gets the first item whose class name is 'blah', and I want it to get the 10th item.

like image 961
Alex Avatar asked Mar 30 '13 13:03

Alex


People also ask

What is the difference between getElementById and getElementsByClassName?

We want to get the unique element and allocate it in a variable this can be done by making use of getElementById. But when we want to get all the products elements and allocate them in a variable then basically we are using getElementByClassName.

What is the use of getElementsByClassName in JavaScript?

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.

Is getElementsByClassName an array?

The result of getElementsByClassName() is not an Array, but an array-like object. Specifically it's called an HTMLCollection , not to be confused with NodeList (which has it's own forEach() method).

What does getElementsByClassName return?

The getElementsByClassName() method returns a collection of elements with a specified class name(s). The getElementsByClassName() method returns an HTMLCollection.


2 Answers

The equivalent of

document.getElementsByClassName('blah')[9].innerHTML = 'blah';

is to use the :eq pseudo-selector:

$(".blah:eq(9)").html('blah');

or the eq function:

$(".blah").eq(9).html('blah');

(...and then the html function to set the inner HTML.)

like image 138
T.J. Crowder Avatar answered Sep 26 '22 09:09

T.J. Crowder


You should also just be able to use jQuery's get() method:

$('.blah').get(9)

jQuery objects also function as indexed arrays as returned elements, so this should also work:

$('.blah')[9]
like image 23
supershnee Avatar answered Sep 24 '22 09:09

supershnee