0

I have got this code snippet:

    var $ispan = $(window.test.document.getElementsByTagName("span"));
    for (var i=5; i<$ispan.size(); i++) {
        $('.content').append('<br>' + $ispan[i].text());
    };

So $ispan contains a collection of spans. I am trying to append a specific selection of those spans to my body. The code is failing at

$ispan[i].text()

Why doesn't this work and how should it be done?

1
  • Start by replacing $(window.test.document.getElementsByTagName("span")); by $('span') Commented Mar 20, 2013 at 8:06

3 Answers 3

2

The square brackets return a specific DOM-node from the jQuery object/collection, rather than a jQuery object; which fails because the native DOM node has no text() method. So, instead, you should use:

$('.content').append('<br>' + $ispan.eq(i).text());

Proof of concept

Note, in the linked 'proof-of-concept,' that I amended the approach to append the elements, switching it to:

$ispan.eq(i).text('span ' + (i+1)).appendTo('.content').before('<br />');

This is because, with the approach written above (which you say works, in the comments) the output was lots of [Object object] in the .content element.

The above alternative finds the relevant element in the jQuery object, sets its text, appends it to the .content element then inserts a <br /> before the appended element.

Also, your original selector should be adequately replaced by $('span'), rather than an over-complicated jQuery-wrapped native DOM selector.

You say, in comments elsewhere, that you need to work on a 'specific set' of span elements, which I'm assuming is why you use the for() {...}, you could instead use :gt():

var $ispan = $("span:gt(4)");
$ispan.text(function (i) {
    return 'span ' + (i + 6);
}).appendTo('.content').before('<br />');

JS Fiddle demo.

References:

Sign up to request clarification or add additional context in comments.

1 Comment

This is working correctly, thank you, will mark for answer in 8 minutes.
0

Try:

var $ispan = $('span');
$ispan.each(function(index) {
    if(index > 3)
       $('.content').append('<br>' + $(this).text());
};

Comments

0

You compiled javascript with jQuery. This is not necessary. Use only javascript or jQuery. It is most recommended. Use eq() to find elements, and start the for() with 0.

Try it:

var ispan = $("span");
    for (var i = 0; i < ispan.length; i++) {
        $('.content').append('<br>' + ispan.eq(i).text());
    };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.