sakuntala
sakuntala

Reputation: 37

Manipulating DOM elements with jQuery and chaining

Playing around with jQuery a bit (sorry, complete noob) I was wondering why this does not work. Maybe I'm not getting the way chaining, context and DOM manipulation works, but I'm just curious. Here it goes:

$("#myDiv")
    .append("h3")
    .append("a")
    .attr("href", "http://example.com")
    .text("Click here")
    .end();

What I would expect to happen:

Instead my page's markup seems to get completely screwed up, although I can't see the dynamic DOM so I'm not sure what's happening. Am I reading the jQuery documentation wrong?

Upvotes: 1

Views: 457

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 185893

Here you go:

$('#myDiv')
    .append($('<h3>')
        .append($('<a>')
            .text('Click here')
            .attr('href', 'http://example.com')));

Live demo: http://jsfiddle.net/HNMET/1/

Notice that the DOM is manipulated upon only once (= when the H3 element is appended to the DIV).


Since the above code is a bit tricky (which makes it a bit confusing I guess), I've broken it down into 3 lines. Note, this is practically the same code, I've only added two "helper" variables to make it more readable:

var anchor, h3;

anchor = $('<a>').text('Click here').attr('href', 'http://example.com');
h3 = $('<h3>').append( anchor );
$('#myDiv').append( h3 );

Live demo: http://jsfiddle.net/HNMET/11/

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

it should be

$("#myDiv")
    .append("<h3>").children('h3:last')
    .append("<a>").children('a:last')
    .attr("href", "http://example.com")
    .text("Click here")

Each method returns the original jQuery object on which it was executed (except for the traversing ones like find, children etc) so you can continue working on them.

I completely removed the .end() since that is only useful if you use the traversing methods that alter the jQuery object.


So your original one, (besides the error that html in append needs tags if you want to add tags) would append a h3 to the #myDiv, then append an a again to the #div, then set an attribute href to the #myDiv and finally sets its text - the #myDivs text ;).

Everything would be done on the #myDiv.

Upvotes: 5

Related Questions