aren55555
aren55555

Reputation: 1717

jQuery, Looping through paragraphs and getting text

So basically with jQuery, I am trying to loop through 3 paragraphs containing tweets. The 3 paragraphs are all of class .tweet-text

For some reason, in the following code, $test2 will be set properly to the first tweet's text, but in the each loop, the js crashes whenver i try to set str. Why is this?

    var $tweets = $(".sidebar-tweet .tweet-text");
    var $test2 = $tweets.text();
    alert($test2);
    $tweets.each(function(i, $tweet){
        var str = $tweet.text();
        alert(str);
    });

I've been trying to debug this with Firebug but to no avail. Thanks for the help.

Upvotes: 0

Views: 3047

Answers (4)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

The second argument to the .each method is not a jquery object, but the actual DOM element.

So you need to wrap it in jQuery again..

var $tweets = $(".sidebar-tweet .tweet-text");
var $test2 = $tweets.text();
alert($test2);
$tweets.each(function(i, tweet){
    var str = $(tweet).text();
    alert(str);
});

demo: http://jsfiddle.net/gaby/xjmZy/

Upvotes: 1

samccone
samccone

Reputation: 10926

var $tweets = $(".sidebar-tweet .tweet-text");

        $tweets.each(function(i, current){
            var str = $(current).text();
            alert(str);
        });

The issue was that the current object is not by defalt a jquery object, you must wrap it $(current) ... to use the jquery methods

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239270

Because $tweet will be a regular javascript object, not a jQuery object. You'll need to wrap it like:

var str = $($tweet).text();

Upvotes: 1

Matthew Cox
Matthew Cox

Reputation: 13672

try this instead

var str = $(this).text();

Upvotes: 1

Related Questions