append()
and prepend()
methods: similar to appendChild, except jQuery accepts a string, a DOM element, or a jQuery object as valid arguments. jQuery converts the argument into a text node or element depending on what is passed.
$("#leftNav ul").append("<li>after the last <li></li>"); // adds <li> at the end of <ul>
$("#leftNav ul").prepend("<li>before the first <li></li>"); // adds <li> at the start of <ul>
$("#leftNav ul").append($("#mainContent h2")); // moves headers from the mainContent to the leftNav
$("#leftNav ul").append($("#mainContent h2").html()); //copies text of the first h2, adds it to leftNav
There are two similar methods — appendTo()
and prependTo()
— which are basically inververted verstions of append()
and prepend()
. A.append(B)
is about equal to B.appendTo(A)
Note: As shown in example 3, if you try to append an element that already exists in the DOM, that element will first be removed from DOM before being reinserted, or appended, in the new location.
before()
and after()
methods: similar to insertBefore()
method (and the non-existant, but found in many javascript libraries, includeing this one, insertAfter()
). The after()
method inserts a node after a selected one. The before()
method inserts a node before a selected one, like the javascript standard method of insertBefore()
.
$("#leftNav ul").before("<h2>Left Navigation</h2>"); // adds header before the <ul>
$("#leftNav ul").after("<h4>New Header</h4>"); // adds header after the <ul>
$("#leftNav h4").before($("#mainContent h2").html()); //copies text of the first h2, adds it to leftNav before our new <h4>
There are two similar methods — insertBefore()
and insertAfter()
— which are basically inververted versions of before()
and after()
. A.before(B)
is about equal to B.insertBefore(A)
Thanks a lot, very clear.
hi,
I would like to ask how about after i prepend() the element and I would like to replace the next text exist inside previous prepend() element?
Is very appreciate if u could reply…
@Kim . Sorry I am not very clear about what you asked. Can you please give an example of what you want to achieve.
sorry for poor explanation about my problem.
I want return message after user do action in same prepend div.
When user checked check box will return some message like “checked success”, the message will display inside a div(“#msg”) and prepend from parent div(“#content”).
If user unchecked again, then will return another message.
The problem now is i will get a new div for each return message.
I want both message display inside same div(“#msg”).
Have any suggestion to solve it?
I have try used setTimeOut() for the div(“#msg”) but it seem not work.
Thanks.
hi.. i thinks i got my solution.
i just put $(‘#msg’).remove() after my ajax function.
thanks for taking time read my comments.
if there is any other better solution I would like to know too.
Nice Solution!!!!!!!!!