02.06.2013 Views

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

52<br />

CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS<br />

Figure 2-14. All text is italicized, <strong>and</strong> the em tags are inside the paragraph tags<br />

.remove() <strong>and</strong> .detach()<br />

To remove an element from the DOM entirely, the .remove() <strong>and</strong> .detach() methods are used. Both<br />

methods remove selected elements from the DOM, but the .detach() method keeps <strong>jQuery</strong> data for the<br />

element intact, which makes it ideal for situations in which an element will be reattached to the DOM at<br />

some point.<br />

Both .remove() <strong>and</strong> .detach() accept an optional selector to filter the elements being removed. In<br />

your example, remove all paragraphs with class foo using the following:<br />

$("p").remove(".foo");<br />

When the code is run, the paragraph with class foo is removed from view <strong>and</strong> is no longer part of the<br />

DOM.<br />

To demonstrate the difference between .remove() <strong>and</strong> .detach(), you’ll have to jump ahead a bit<br />

<strong>and</strong> use a method called .data(), which allows developers to attach information to an element without<br />

adding additional tags or attributes .data() will be covered more thoroughly in the next section.)<br />

First, add some data to the first paragraph in the DOM. Then, with the data added, remove the<br />

element from the DOM using .detach(), reattach it, <strong>and</strong> attempt to read the data:<br />

$("p:first").data("test","This is some data.");<br />

var p = $("p:first").detach();<br />

console.log("Data stored: "+p.data("test"));

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!