How to get innerHTML for a particular html element through its class in jQuery?
Asked Answered
M

3

9

I have HTML code like this:

<div class="a">html value 1</div>

<div class="a">html value 2</div>

How can I access html value 1 and html value 2 using jquery?

Monogram answered 26/7, 2012 at 9:43 Comment(2)
Code like what? Give a proper code example or it will be hard to understand what you actually mean.Juliojulis
i am new to stack overflow. that's why such mistake happenedMonogram
G
6
$('.a')[0].innerHTML;
$('.a')[1].innerHTML;

FIDDLE

Grussing answered 26/7, 2012 at 9:55 Comment(1)
Iam wondering when he wanted to use this method then why don't he use Javascript onlySynecdoche
G
7

Separately:

$('div.a:eq(0)').html(); // $('div.a:eq(0)').text();
$('div.a:eq(1)').html(); // $('div.a:eq(1)').text();

Using loop:

$('div.a').each(function() {
   console.log( $(this).html() ); //or $(this).text();
});

Using .html()

​$('div.a').html(function(i, oldHtml) {
  console.log( oldHtml )
})​​;

DEMO

Using .text()

$('div.a').text(function(i, oldtext) {
  console.log( oldtext )
})​;

DEMO

Gainer answered 26/7, 2012 at 9:48 Comment(0)
G
6
$('.a')[0].innerHTML;
$('.a')[1].innerHTML;

FIDDLE

Grussing answered 26/7, 2012 at 9:55 Comment(1)
Iam wondering when he wanted to use this method then why don't he use Javascript onlySynecdoche
W
0

Try this:

var a = document.getElementsByClassName('a');
for (var i = 0; i < a.length; i++) {
    alert(a[i].innerHTML)
}

demo

Weinberg answered 26/7, 2012 at 9:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.