1

I am new to JQuery. I wrote a small piece of code (fiddle). I was wondering if someone could throw some light on the order of execution of the statements i wrote.

The HTML:

<span>I</span>
<span>Love</span>
<span>JQuery</span>

​The JavaScript:

$(function() {
    $('<a>Url</a>').attr('href', 'http://www.jquery.com').appendTo('body');
    $('<span>More</span>').appendTo('body');
    $('span'.text());
});​

I was expecting an output of Url I Love JQuery More but the output, as you can see, is I Love JQuery UrlMore. Why is the output in that order? Please help

4
  • 1
    What are you expecting the last line $('span'.text()) to do? Commented Aug 21, 2012 at 18:53
  • I think you may be confused because you expect $('span'.text()); to be doing something. It does nothing (except possibly throw an error).
    – Shmiddty
    Commented Aug 21, 2012 at 18:55
  • With $('span'.text()), I am appending text in all 'span' tags. Commented Aug 21, 2012 at 19:16
  • gotcha.. my mistake.. it should be $('span').text() Commented Aug 21, 2012 at 19:18

4 Answers 4

2

appendTo inserts an element to the end of the target. If you want to insert an element to the beginning of the target, use prependTo instead:

$(function() {
    $('<a>Url</a>').attr('href','http://www.jquery.com').prependTo('body');
    $('<span>More</span>').appendTo('body');  
});​

This way, <a>Url</a> gets inserted at the beginning of body, and <span>More</span> at the end, yielding your expected string Url I Love JQuery More.

DEMO.

In your fiddle, there's also this line $('span'.text()); which is wrong. To obtain the text of a span, use $('span').text() instead.

1
  • @StrubT: Thanks, I've included it in my answer. Commented Aug 21, 2012 at 18:54
1

You are appending to the body, which adds it to the end. Append means that, by default, it will add it to the end of the text. Therefore, it's in three chunks.

I love JQuery --append-- URL --append-- More

0

After your document is loaded, Then the $(function(){}) section get executed. You try to append 'Url' and 'More' to the end of the document body, That's why 'UrlMore' is show after your initial HTML document.

0

As already explained, appendTo inserts at the end.
I personaly prefer working like this:

$('#mysample').prepend($('<a href="jquery">URL</a>')).append($('<span>More</span>'));

I first select my wrapper, and then tell what i want appended to it. This allows you to chain your actions as i did in the example. Also there is no need to add the attributes in a separate action, you can do it upon construction as i did.

the fiddle: http://jsfiddle.net/dSL6S/11/

Not the answer you're looking for? Browse other questions tagged or ask your own question.