jquery get elements by class name

7.1k views Asked by At

I'm using Jquery to get a list of elements having a class "x".

html:

<p class="x">Some content</p>
<p class="x">Some content#2</p>

If we use Jquery to get both these html elements and do something with it- we use something like:

$(".x").text("changed text");

This will change the text of both the paragraphs. From $(".x") - How can we add a array - subscript notation like we can do with getElementsByclassName as follows:

document.getElementsByClassName("x")[0].innerHTML

I tried this $(".x")[0].text("asasa")- it doesn't work gives a typeerror in javascript console. I also tried get API here -http://jsfiddle.net/probosckie/jnz825mp/ - and it doesnt work

the error is Uncaught TypeError: $(...).get(...).text is not a function None of the solutions below WORK!

3

There are 3 answers

2
Zexi Li On BEST ANSWER

You can do it like this way:

$('.x:eq(0)').text('changed text');

or:

$('.x').eq(1).text('bbb');

both works well

sorry for my before answer..

6
alesc On

You can use the get() method for accessing an element from the array, for example:

$(".x").get(index).textContent = "changed text";

More info: https://api.jquery.com/jquery.get/

And for obtaining HTML (innerHTML) you call the .html() function:

// This is equal to document.getElementsByClassName("x")[0].innerHTML
$(".x").get(0).innerHTML;

If you want to set the HTML, then just provide your HTML code inside the function call like this .html('<h1>Hello, World!</h1>').

EDIT: .get() returns the DOM object not the jQuery wrapped element. Therefore .text() and .html() doesn't work. Unless you wrap it.

More options:

$(".x").get(0).innerHTML;
$($(".x").get(0)).html();
$(".x:first").html();
0
Royi Namir On

The solution $(".x").get(index)... will first match all .x (which is bad performance). And then it will filter

If you have 1000 .x it will fill an 1000 items in the jQuery object (before filtered)

But

$(".x:first").text("changed text"); will do better because it won't yield all .x and then filter , but will do it at a first single step (without filling 1000 items)