最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get Inner HTML of Multiple Elements - Stack Overflow

programmeradmin2浏览0评论

I want to get the content of multiple Spans. Here is my code:

/

It's supposed to give me "111, 222, 333, 444". It gives me "undefined" instead.

What's wrong with my code?

I want to get the content of multiple Spans. Here is my code:

http://jsfiddle/4XumV/

It's supposed to give me "111, 222, 333, 444". It gives me "undefined" instead.

What's wrong with my code?

Share Improve this question asked Feb 20, 2012 at 6:46 BayuBayu 4672 gold badges10 silver badges19 bronze badges 1
  • 2 Please include the relevant code within your question. – James Montagne Commented Feb 20, 2012 at 6:48
Add a ment  | 

8 Answers 8

Reset to default 3

Well, you weren't actually getting the innerHTML property, you were getting an undefined html property. Change it to innerHTML and it will work.

http://jsfiddle/4XumV/1/

This should work:

$(function()
{
    var allLatestNews = $("#main").find('span');
    $.each(allLatestNews, function(i,val){
        alert($(val).text());
    });
});

I was wondering WHY your code wasn't working and JQuery does return an array of elements from the selector, this could have also worked:

for(var i = 0; i < allLatestNews.length; i++)
{
    alert($(allLatestNews[i]).text());
}

First wrap the element as a JQuery object and then querying text() not html, which is accessed by a function not a property.

Your updated fiddle: http://jsfiddle/4XumV/9/

You seem to be confusing jquery's html with innerHTML.

You can either use innerHTML:

http://jsfiddle/4XumV/3/

alert(allLatestNews[i].innerHTML);

or jquery's html:

http://jsfiddle/4XumV/5/

alert(allLatestNews.eq(i).html());

Try this it should work

     allLatestNews.each(function()
     {
      alert($(this).html());
     });
var $elms = $('#main').find('span');
$elms.each(function(){ alert($(this).text()); });

http://jsfiddle/4XumV/2/

This is working

var allLatestNews = $("#main").find('span');

    $.each(allLatestNews ,function( index , value){
    console.log($(value).html());
    });

instead of console.log($(value).html()); you can write alert($(value).html());

The property of a DOM element to return the inner HTML is named innerHTML not html

allLatestNews[i].innerHTML 

Or using jQuery

$(allLatestNews[i]).html()

Updated JS Fiddle

you can also use this

    var allLatestNews = $(this).find("#main span");

    for(var i = 0; i < allLatestNews.length; i++)
    {
        alert(allLatestNews[i].innerHTML);
    }
发布评论

评论列表(0)

  1. 暂无评论