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:
- Select
#myDiv - Insert an H3 inside it
- Then inside the H3, insert an A tag
- Set the A tag’s HREF attribute to a URL
- And then set the A tag’s text to “Click Here”
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?
it should be
Each method returns the original jQuery object on which it was executed (except for the traversing ones like
find,childrenetc) 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
h3to the#myDiv, then append anaagain to the#div, then set an attributehrefto the#myDivand finally sets its text – the#myDivstext 😉.Everything would be done on the
#myDiv.