|
| 1 | +--- |
| 2 | +chapter : jqfundamentals |
| 3 | +section : 6 |
| 4 | +title : Manipulating Elements |
| 5 | +attribution: jQuery Fundamentals |
| 6 | +--- |
| 7 | +## Manipulating Elements |
| 8 | + |
| 9 | +Once you've made a selection, the fun begins. You can change, move, remove, and clone elements. |
| 10 | +You can also create new elements via a simple syntax. |
| 11 | + |
| 12 | +For complete documentation of jQuery manipulation methods, visit [http://api.jquery.com/category/manipulation/](http://api.jquery.com/category/manipulation/ "Manipulation documentation on api.jquery.com"). |
| 13 | + |
| 14 | +### Getting and Setting Information about Elements |
| 15 | + |
| 16 | +There are any number of ways you can change an existing element. |
| 17 | +Among the most common tasks you'll perform is changing the inner HTML or attribute of an element. |
| 18 | +jQuery offers simple, cross-browser methods for these sorts of manipulations. |
| 19 | +You can also get information about elements using many of the same methods in their getter incarnations. |
| 20 | +We'll see examples of these throughout this section, but specifically, here are a few methods you can use to get and set information about elements. |
| 21 | + |
| 22 | +<div class="note" markdown="1"> |
| 23 | +### Note |
| 24 | + |
| 25 | +Changing things about elements is trivial, but remember that the change will affect all elements in the selection. |
| 26 | +If you just want to change one element, be sure to specify that in the selection before calling a setter method. |
| 27 | +</div> |
| 28 | + |
| 29 | +<div class="note" markdown="1"> |
| 30 | +Note |
| 31 | + |
| 32 | +When methods act as getters, they generally only work on the first element in the selection. |
| 33 | +They do not return a jQuery object, so you can't chain additional methods to them. |
| 34 | +One notable exception is `$.fn.text`; as mentioned below, it gets the text for all elements in the selection. |
| 35 | +</div> |
| 36 | + |
| 37 | +#### $.fn.html |
| 38 | +Get or set the html contents. |
| 39 | + |
| 40 | +#### $.fn.text |
| 41 | +Get or set the text contents; HTML will be stripped. |
| 42 | + |
| 43 | +#### $.fn.attr |
| 44 | +Get or set the value of the provided attribute. |
| 45 | + |
| 46 | +#### $.fn.width |
| 47 | +Get or set the width in pixels of the first element in the selection as an integer. |
| 48 | + |
| 49 | +#### .fn.height |
| 50 | +Get or set the height in pixels of the first element in the selection as an integer. |
| 51 | + |
| 52 | +#### fn.position |
| 53 | +Get an object with position information for the first element in the selection, relative to its first positioned ancestor. _This is a getter only_. |
| 54 | + |
| 55 | +#### $.fn.val |
| 56 | +Get or set the value of form elements. |
| 57 | + |
| 58 | +<div class="example" markdown="1"> |
| 59 | +Changing the HTML of an element |
| 60 | + |
| 61 | + $('#myDiv p:first') |
| 62 | + .html('New <strong>first</strong> paragraph!'); |
| 63 | +</div> |
| 64 | + |
| 65 | +### Moving, Copying, and Removing Elements |
| 66 | + |
| 67 | +There are a variety of ways to move elements around the DOM; generally, there are two approaches: |
| 68 | + |
| 69 | +* Place the selected element(s) relative to another element |
| 70 | + |
| 71 | +* Place an element relative to the selected element(s) |
| 72 | + |
| 73 | +For example, jQuery provides `$.fn.insertAfter` and `$.fn.after`. The `$.fn.insertAfter` method places the selected element(s) after the element that you provide as an argument; |
| 74 | +the `$.fn.after` method places the element provided as an argument after the selected element. |
| 75 | +Several other methods follow this pattern: `$.fn.insertBefore` and `$.fn.before`; |
| 76 | +`$.fn.appendTo` and `$.fn.append`; and `$.fn.prependTo` and `$.fn.prepend`. |
| 77 | + |
| 78 | +The method that makes the most sense for you will depend on what elements you already have selected, and whether you will need to store a reference to the elements you're adding to the page. |
| 79 | +If you need to store a reference, you will always want to take the first approach — placing the selected elements relative to another element — as it returns the element(s) you're placing. |
| 80 | +In this case, `$.fn.insertAfter`, `$.fn.insertBefore`, `$.fn.appendTo`, and `$.fn.prependTo` will be your tools of choice. |
| 81 | + |
| 82 | +<div class="example" markdown="1"> |
| 83 | +Moving elements using different approaches |
| 84 | + |
| 85 | + // make the first list item the last list item |
| 86 | + var $li = $('#myList li:first').appendTo('#myList'); |
| 87 | + |
| 88 | + // another approach to the same problem |
| 89 | + $('#myList').append($('#myList li:first')); |
| 90 | + |
| 91 | + // note that there's no way to access the |
| 92 | + // list item that we moved, as this returns |
| 93 | + // the list itself |
| 94 | +</div> |
| 95 | + |
| 96 | +### Cloning Elements |
| 97 | + |
| 98 | +When you use methods such as `$.fn.appendTo`, you are moving the element; sometimes you want to make a copy of the element instead. |
| 99 | +In this case, you'll need to use `$.fn.clone` first. |
| 100 | + |
| 101 | +<div class="example" markdown="1"> |
| 102 | +Making a copy of an element |
| 103 | + |
| 104 | + // copy the first list item to the end of the list |
| 105 | + $('#myList li:first').clone().appendTo('#myList'); |
| 106 | +</div> |
| 107 | + |
| 108 | +<div class="note" markdown="1"> |
| 109 | +### Note |
| 110 | + |
| 111 | +If you need to copy related data and events, be sure to pass true as an argument to `$.fn.clone`. |
| 112 | +</div> |
| 113 | + |
| 114 | +### Removing Elements |
| 115 | + |
| 116 | +There are two ways to remove elements from the page: `$.fn.remove` and `$.fn.detach`. |
| 117 | +You'll use `$.fn.remove` when you want to permanently remove the selection from the page; |
| 118 | +while the method does return the removed element(s), those elements will not have their associated data and events attached to them if you return them to the page. |
| 119 | + |
| 120 | +If you need the data and events to persist, you'll want to use `$.fn.detach` instead. |
| 121 | +Like `$.fn.remove`, it returns the selection, but it also maintains the data and events associated with the selection, so you can restore the selection to the page at a later time. |
| 122 | + |
| 123 | +<div class="note" markdown="1"> |
| 124 | +###Note |
| 125 | + |
| 126 | +The `$.fn.detach` method is extremely valuable if you are doing heavy manipulation to an element. |
| 127 | +In that case, it's beneficial to `$.fn.detach` the element from the page, work on it in your code, and then restore it to the page when you're done. |
| 128 | +This saves you from expensive "DOM touches" while maintaining the element's data and events. |
| 129 | +</div> |
| 130 | + |
| 131 | +If you want to leave the element on the page but simply want to remove its contents, you can use `$.fn.empty` to dispose of the element's inner HTML. |
| 132 | + |
| 133 | +### Creating New Elements |
| 134 | + |
| 135 | +jQuery offers a trivial and elegant way to create new elements using the same `$()` method you use to make selections. |
| 136 | + |
| 137 | +<div class="example" markdown="1"> |
| 138 | +Creating new elements |
| 139 | + |
| 140 | + $('<p>This is a new paragraph</p>'); |
| 141 | + $('<li class="new">new list item</li>'); |
| 142 | +</div> |
| 143 | + |
| 144 | +<div class="example" markdown="1"> |
| 145 | +Creating a new element with an attribute object |
| 146 | + |
| 147 | +$('<a/>', { |
| 148 | + html : 'This is a <strong>new</strong> link', |
| 149 | + 'class' : 'new', |
| 150 | + href : 'foo.html' |
| 151 | +}); |
| 152 | +</div> |
| 153 | + |
| 154 | +Note that in the attributes object we included as the second argument, the property name class is quoted, while the property names text and href are not. |
| 155 | +Property names generally do not need to be quoted unless they are reserved words (as class is in this case). |
| 156 | + |
| 157 | +When you create a new element, it is not immediately added to the page. |
| 158 | +There are several ways to add an element to the page once it's been created. |
| 159 | + |
| 160 | +<div class="example" markdown="1"> |
| 161 | +Getting a new element on to the page |
| 162 | + |
| 163 | + var $myNewElement = $('<p>New element</p>'); |
| 164 | + $myNewElement.appendTo('#content'); |
| 165 | + |
| 166 | + $myNewElement.insertAfter('ul:last'); // this will remove the p from #content! |
| 167 | + $('ul').last().after($myNewElement.clone()); // clone the p so now we have 2 |
| 168 | +</div> |
| 169 | + |
| 170 | +Strictly speaking, you don't have to store the created element in a variable — you could just call the method to add the element to the page directly after the `$()`. |
| 171 | +However, most of the time you will want a reference to the element you added, so you don't need to select it later. |
| 172 | + |
| 173 | +You can even create an element as you're adding it to the page, but note that in this case you don't get a reference to the newly created element. |
| 174 | + |
| 175 | +<div class="example" markdown="1"> |
| 176 | +Creating and adding an element to the page at the same time |
| 177 | + |
| 178 | + $('ul').append('<li>list item</li>'); |
| 179 | +</div> |
| 180 | + |
| 181 | +<div class="note" markdown="1"> |
| 182 | +### Note |
| 183 | + |
| 184 | +The syntax for adding new elements to the page is so easy, it's tempting to forget that there's a huge performance cost for adding to the DOM repeatedly. If you are adding many elements to the same container, you'll want to concatenate all the html into a single string, and then append that string to the container instead of appending the elements one at a time. You can use an array to gather all the pieces together, then join them into a single string for appending. |
| 185 | + |
| 186 | +<div class="example" markdown="1"> |
| 187 | + var myItems = [], $myList = $('#myList'); |
| 188 | + |
| 189 | + for (var i=0; i<100; i++) { |
| 190 | + myItems.push('<li>item ' + i + '</li>'); |
| 191 | + } |
| 192 | + |
| 193 | + $myList.append(myItems.join('')); |
| 194 | +</div> |
| 195 | +</div> |
| 196 | + |
| 197 | +### Manipulating Attributes |
| 198 | + |
| 199 | +jQuery's attribute manipulation capabilities are extensive. |
| 200 | +Basic changes are simple, but the `$.fn.attr` method also allows for more complex manipulations. |
| 201 | +It can either set an explicit value, or set a value using the return value of a function. |
| 202 | +When the function syntax is used, the function receives two arguments: |
| 203 | +the zero-based index of the element whose attribute is being changed, and the current value of the attribute being changed. |
| 204 | + |
| 205 | +<div class="example" markdown="1"> |
| 206 | +Manipulating a single attribute |
| 207 | + |
| 208 | + $('#myDiv a:first').attr('href', 'newDestination.html'); |
| 209 | +</div> |
| 210 | + |
| 211 | +<div class="example" markdown="1"> |
| 212 | +Manipulating multiple attributes |
| 213 | + |
| 214 | + $('#myDiv a:first').attr({ |
| 215 | + href : 'newDestination.html', |
| 216 | + rel : 'super-special' |
| 217 | + }); |
| 218 | +</div> |
| 219 | + |
| 220 | +<div class="example" markdown="1"> |
| 221 | +Using a function to determine an attribute's new value |
| 222 | + |
| 223 | + $('#myDiv a:first').attr({ |
| 224 | + rel : 'super-special', |
| 225 | + href : function(idx, href) { |
| 226 | + return '/new/' + href; |
| 227 | + } |
| 228 | + }); |
| 229 | +</div> |
| 230 | + |
| 231 | +<div class="example" markdown="1"> |
| 232 | + $('#myDiv a:first').attr('href', function(idx, href) { |
| 233 | + return '/new/' + href; |
| 234 | + }); |
| 235 | +</div> |
0 commit comments