Jquery add, append, prepend, remove child

Starting from child element: appendTo, prependTo

Add at the end the selected item to a jquery container. This sintax return the element added, so it can be use in fluent syntax. In this case appendTo or prependTo return liElment.

var liElement = "<li>test</li>";
$(liElement).appendTo($('#ulContainer')).click(deleteIt)

Prepend will add the element as first child.

$(liElement).prependTo($('#ulContainer')).click(deleteIt)

Starting from parent: append, prepend

Otherwise starting from parent element

var liElement = "<li>test</li>";
liElement.click(deleteIt)
$('#ulContainer').append(liElement)
$('#ulContainer').prepend(liElement)

These lines of code return $(‘#ulContainer’) object so to add event to the child is necessary add its separately.

Starting from child: remove

If you have already the child to remove you only need to call remove without any parameter.
To complete the first example where I add deleteIt function in response of click, here is the right code

function deleteIt() {
   // this: the item clicked
   $ (this).remove();
}

Starting from parent: remove

Starting from parent, the remove syntax permit to specify a selector to find his children

$('#ulContainer').remove("li:last")
Annunci

Informazioni su Andrea Regoli

Project Manager .Net Developer WPF WP7 Asp.Net c# javascript ajax SQL sharepoint
Questa voce è stata pubblicata in HTML5, javascript, jquery e contrassegnata con , , , , . Contrassegna il permalink.

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...