Last updated .
To set or get attributes on a DOM element, you use one and the same function, called attr. When setting an attribute value this way, it will usually cause an immediate update to the same property and thus also an immediate visual update, if the value has anything to do with what the page displays. The function can be used in three different ways:
value = attr(name)
. This is used to get an attribute value. The function returns a string.attr(name, value)
. This is used to set a single attribute value.attr(object)
. This is used to set multiple attribute values in one go. The attribute values are taken from the named properties of the object that is passed in.An example of retrieving an attribute value:
<span id="s0" lang="ja"></span>
<script>
var $s0 = jQuery("#s0");
var value = $s0.attr("LANG");
console.log(value); // ja
</script>
An example of setting attribute values on two elements:
<span lang="ja">Text</span>
<span lang="de">Text</span>
<script>
var $spans = jQuery("span");
var attributes = { lang: "en", title: "English", };
$spans.attr(attributes);
console.log($spans.get(1).title); // English
</script>
The removeAttr function is used to remove one or more attributes: removeAttr(names)
, where the single argument is a string containing a space-delimited list of attribute names. An example:
<span id="s0" lang="ja" title="Japanese">Text</span>
<script>
var $s0 = jQuery("#s0");
$s0.removeAttr("lang title");
console.log($s0.get(0).title); // (An empty string
</script>
Of course, in the above example, the lang and title attributes are not really removed, only their values are cleared to their default. Only if you remove a homegrown attribute, which is not part of the HTML specification, is it removed for real.
To set or get properties on a DOM element, you use one and the same function, called prop. When setting a property value this way, it will usually cause an immediate update to the same attribute and also an immediate visual update, if the value has anything to do with what the page displays. The function can be used in three different ways:
value = prop(name)
. This is used to get a property value. Oddly, the name parameter is case-sensitive, unlike with the attr method. Of course, this method may be called
on a jQuery set containing any number of elements. The method simply returns the property value of the first element.prop(name, value)
. This is used to set a single property. The second parameter can be of any type, including a function (see example below) returning a new property value.prop(object)
. This is used to set multiple properties in one go. The property values are taken from the named properties of the object that is passed in.An example of setting and then retrieving a property value:
<span id="s0" lang="ja"></span>
<script>
var $s0 = jQuery("#s0");
$s0.prop("lang", "en");
var value = $s0.prop("lang");
console.log(value); // en
</script>
The below snippet is an example of setting a property using a custom function. The function takes the index of the element in the jQuery set as its first argument, and the current property value as its second argument. In addition, the this variable is set to reference the element in question. The function must return the new property value.
<span id="s0" title="aTitle"></span>
<script>
var $s0 = jQuery("#s0, #s1");
$s0.prop("title", function (index, val)
{
return this.id + ":" + val + ":" + index;
}
);
var value = $s0.prop("title");
console.log(value); // s0:aTitle:0
</script>
The removeProp function is used to remove a single property: removeProp(name)
, where the single argument is a string containing a property name. An example:
<span id="s0" title="Japanese">Text</span>
<script>
var $s0 = jQuery("#s0");
$s0.removeProp("title");
console.log($s0.prop("title")); // Japanese
$s0.prop("custom", "whatever");
console.log($s0.prop("custom")); // whatever
$s0.removeProp("custom");
console.log($s0.prop("custom")); // undefined
</script>
As the above example shows, the title property isn't removed at all! This must be because the browser does not allow it. On the other hand, removing a custom property succeeds.
According to the HTML5 specification, it is possible to adorn an element with custom data in attributes. This feature often comes in handy in various scripting scenarios. The name of such an attribute must start with the letters "data-", e.g. "data-custom". jQuery reads these attributes and allows you to read and manipulate these data using the data method. jQuery is clever enough to guess the type of the data.
The function can be used in three different ways:value = data(name)
. This is used to get a property value that may or may not originate from a data-x attribute. data(name, value)
. This is used to set a single property value.data(object)
. This is used to set multiple properties in one go. The property names and values are taken from the named properties of the object that is passed in.In dealing with these properties, jQuery strips the "data-" part from property names. Also, the property name will be camelCased, for example a "data-build-number" attribute will result in a "buildNumber" property. An example:
<span id="s0" data-build-number="214"></span>
<script>
var $s0 = jQuery("#s0");
var value = $s0.data("buildNumber");
console.log(value); // 214
var type = typeof (value);
console.log(type); // number
</script>
The above example demonstrates how jQuery transform "data-x" attribute names into property names and also that the value is correctly interpreted to be a number.
Note that, once values have been read from the attributes, there is no longer any link between attributes and properties read with the data function, as this example shows:
<span id="s0" data-build-number="214"></span>
<script>
var $s0 = jQuery("#s0");
var value = $s0.data("buildNumber");
console.log(value); // 214
$s0.data("buildNumber", 215);
value = $s0.data("buildNumber");
console.log(value); // 215
value = $s0.attr("data-build-number");
console.log(value); // 214
</script>
The removeData function is used to remove a single property or all properties: removeData([name])
, where the single argument is a string containing
one or more property names (separated with the space character) or an array of property names. If the argument is omitted, all the data properties are removed. An example:
<span id="s0" data-build-number="214"></span>
<script>
var $s0 = jQuery("#s0");
$s0.data("buildNumber", 215); // update value
$s0.data("anotherProperty", ""); // create data property
$s0.removeData("buildNumber");
$s0.removeData("anotherProperty");
value = $s0.data("buildNumber");
console.log(value); // 214
value = $s0.data("anotherProperty");
console.log(value); // undefined
</script>
As the example shows, a data property which is backed by an attribute is not really removed - instead it reverts back to the attribute value.
The addClass method can be used to add one or more class names to the class property of an element. The syntax is addClass(names)
, where the single argument is a string containing
one or more class names (separated with the space character). Or, one can pass a function for that single argument. The function must return a string of class names, and takes the element index and the element itself as arguments. An example:
<span id="s0" class="class1"></span>
<script>
var $s0 = jQuery("#s0");
$s0.addClass("class2 class1");
var value = document.getElementById("s0").className;
console.log(value); // class1 class2
</script>
With the ability to add classes dynamically, it is natural that you can remove the same classes with the removeClass method. The syntax is removeClass(names)
, where the single argument is a string containing
one or more class names (separated with the space character) or a function (see the addClass method for details). An example:
<span id="s0" class="class1 class2"></span>
<script>
var $s0 = jQuery("#s0");
$s0.removeClass("class1");
var value = document.getElementById("s0").className;
console.log(value); // class2
</script>
A common pattern is the toggling of class between two class names. The toggleClass method exists for that very purpose and has this signature: toggleClass([names] [,bSwitch])
.
The first, optional parameter specifies one or more class names; if the element in question does not have the class, it is added to the class property, otherwise it is removed from the class property. The first parameter has these variations:
function(/*integer*/index, /*string*/classNames, /*boolean*/bSwitch) : string
. Index is the index of the element in the jQuery set, classNames
contains the current class names, and bSwitch is the value of the parameter of the same name in the call of toggleClass. In addition, the this variable will be set to reference the DOM element.The bSwitch parameter is also optional and you can pass three different values:
The next example shows a simple example of toggling two classes:
<span id="s0" class="class1 class2"></span>
<script>
var $s0 = jQuery("#s0");
$s0.toggleClass("class2 class3");
var value = document.getElementById("s0").className;
console.log(value); // class1 class3
$s0.toggleClass("class2 class3");
var value = document.getElementById("s0").className;
console.log(value); // class1 class2
</script>
The following snippet exemplifies using the bSwitch parameter to add class names:
<span id="s0" class="class1 class2"></span>
<script>
var $s0 = jQuery("#s0");
$s0.toggleClass("class2 class3", true);
var value = document.getElementById("s0").className;
console.log(value); // class1 class2 class3
</script>
To set or get styles on a DOM element, you use one and the same function, called css. To get style values: var style = jQuerySet.css(names)
. To set values use: jQuerySet.css(name, value)
or jQuerySet.css(values)
. The function can be used in three different ways:
value = css(name)
. This is used to get one or more style values. The function returns a string, or, if multiple styles are called for, an object containing the styles as name-value pairs.css(name, value)
. This is used to set a single attribute value. The value parameter is either a string or a function returning the value for the style, with this signature:
function(/*integer*/index, /*object*/element) : string
. Index is the index of the element in the jQuery set and element is a reference to the element in question.
In addition, the this variable will be set to reference the DOM element. Note that number values are converted to string, with "px" appended.css(object)
. This is used to set multiple style values in one go. Any property value in this object may be function - in which case it must be of the signature function(/*integer*/index, /*string*/currentValue) : string
(see third example below).
The style values are taken from the named properties of the object that is passed in.In specifying style names, the css and DOM formatting are both supported (e.g. foreground-color vs. foregroundColor). jQuery allows for a nice shortcut when setting numeric values: You can pass a formula, e.g. "+=10" for numeric properties, in this case to increase the value by 10 px.
An example of retrieving a number of style values:
<span id="s0" style="position:relative;left:10px;top:10px;"></span>
<script>
var $s0 = jQuery("#s0");
var styles= $s0.css(["position", "left"]);
console.log(styles); // Object { position="relative", left="10px"}
</script>
An example of setting style values:
<span id="s0" style="position:relative;left:10px;"></span>
<script>
var $s0 = jQuery("#s0");
$s0.css("left", 5);
var styles = $s0.css("left");
console.log(styles); // 5px
</script>
The next example demonstrates using a function inside a composite object to set the left style property:
<span id="s0" style="position:relative;left:10px;"></span>
<script>
var $s0 = jQuery("#s0");
$s0.css(
{
"padding": 2,
"left": function (index, currentValue)
{
return 0.9 * parseInt(currentValue);
}
}
);
var styles = $s0.css(["left", "padding-left"]);
console.log(styles); // Object { left="9px", padding-left="2px" }
</script>
Instead of using the css method to get or set element width, jQuery offers the width method dedicated to this purpose. It returns the computed width, i.e.
the value that is current at any time. The value returned (or set) with this method represents the smallest kind of width for the element, in that it excludes padding, border and margin (see diagram).
To get the width in pixels: var width = jQuerySet.width()
. This returns the width as a number (in pixels). To set width use: jQuerySet.width(value)
. The value can be a number, which jQuery then
takes to be pixels. If you want to define the width in another unit, pass a string with the type of unit appended, e.g. "200em". The value may also be a function, which is then expected to return the value for the width. The function must have the
signature function(/*integer*/ index, /*object*/ element)
, where index is the index in the jQuery set of the element in question, and element is a reference to that element. In addition,
the this variable is set to point to the same element (see this example). An example that sets and gets the width:
<div id="d0">
jQuery is a fast, small, and feature-rich JavaScript library. It makes things
like HTML document traversal and manipulation, event handling, animation, and
Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
With a combination of versatility and extensibility, jQuery has changed the way
that millions of people write JavaScript.
</div>
<script>
var $d0 = jQuery("#d0");
$d0.width(1000);
var width = $d0.width();
console.log(width); // 1000
</script>
This method returns or sets the computed inner width, i.e.
the value that is current at any time. The value returned (or set) with this method represents the width of the element including padding, but excluding border and margin (see diagram).
To get the inner width in pixels: var innerWidth = jQuerySet.innerWidth()
. This returns the inner width as a number (in pixels). To set inner width use: jQuerySet.innerWidth(value)
. The value can be a number, which jQuery then
takes to be pixels. If you want to define the inner width in another unit, pass a string with the type of unit appended, e.g. "200em". The value may also be a function, which is then expected to return the value for the inner width. The function must have the
signature function(/*integer*/ index, /*object*/ element)
, where index is the index in the jQuery set of the element in question, and element is a reference to that element. In addition,
the this variable is set to point to the same element (see this example). An example that sets and gets the width and inner width:
<div id="d0" style="width:700px;padding:7px;">
jQuery is a fast, small, and feature-rich JavaScript library.
</div>
<script>
var $d0 = jQuery("#d0");
var width = $d0.width();
console.log(width); // 700
var innerWidth = $d0.innerWidth();
console.log(innerWidth); // 71
</script>
This method returns or sets the computed outer width, i.e.
the value that is current at any time. The value returned (or set) with this method represents the width of the element including padding and border, but without any margin (see diagram).
To get the outer width in pixels: var outerWidth = jQuerySet.outerWidth([withMargin])
. This returns the outer width as a number (in pixels), optionally including the margin. To set outer width use: jQuerySet.outerWidth(value)
. The value can be a number, which jQuery then
takes to be pixels. If you want to define the outer width in another unit, pass a string with the type of unit appended, e.g. "200em". The value may also be a function, which is then expected to return the new value for the outer width. The function must have the
signature function(/*integer*/ index, /*object*/ element)
, where index is the index in the jQuery set of the element in question, and element is a reference to that element. In addition,
the this variable is set to point to the same element (see this example). In the next example, width, outer width and outer width including margin
are obtained. After increasing the outer width by 20 px, the same properties are queried again:
<div id="d0" style="width:700px;padding:7px;border:3px solid;margin:2px;">
jQuery is a fast, small, and feature-rich JavaScript library.
</div>
<script>
var $d0 = jQuery("#d0");
var width = $d0.width();
console.log(width); // 700
var outerWidth = $d0.outerWidth(true);
console.log(outerWidth); // 724
outerWidth = $d0.outerWidth();
console.log(outerWidth); // 720
$d0.outerWidth(740); // Increase outer height by 20 px
width = $d0.width();
console.log(width); // 720
outerWidth = $d0.outerWidth(true);
console.log(outerWidth); // 744
outerWidth = $d0.outerWidth();
console.log(outerWidth); // 740
</script>
To set or get element height, use the height method. It works in the same way as the width method.
The value returned (or set) with this method represents the smallest kind of height for the element, in that it excludes padding, border and margin (see diagram).
To get the height in pixels: var height = jQuerySet.height()
. This returns the height as a number (in pixels). To set height use: jQuerySet.height(value)
. The value can be a number, which jQuery then
takes to be pixels. If you want to define the height in another unit, pass a string with the type of unit appended, e.g. "200em". The value may also be a function, which is then expected to return the value for the height. The function must have the
signature function(/*integer*/ index, /*object*/ element)
, where index is the index in the jQuery set of the element in question, and element is a reference to that element. In addition,
the this variable is set to point to the same element. An example that gets and sets the height, using a function:
<div id="d0">
jQuery is a fast, small, and feature-rich JavaScript library. It makes things
like HTML document traversal and manipulation, event handling, animation, and
Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
With a combination of versatility and extensibility, jQuery has changed the way
that millions of people write JavaScript.
</div>
<script>
var $d0 = jQuery("#d0");
$d0.height(function (/*integer*/ index, /*object*/ element)
{
return window.innerHeight * 0.2;
}
);
var height = $d0.height();
console.log(height);
</script>
This method returns or sets the computed inner height, i.e.
the value that is current at any time. The value returned (or set) with this method represents the height of the element including padding, but excluding border and margin (see diagram).
To get the inner height in pixels: var innerHeight = jQuerySet.innerHeight()
. This returns the inner height as a number (in pixels). To set inner height use: jQuerySet.innerHeight(value)
. The value can be a number, which jQuery then
takes to be pixels. If you want to define the inner height in another unit, pass a string with the type of unit appended, e.g. "200em". The value may also be a function, which is then expected to return the value for the inner height. The function must have the
signature function(/*integer*/ index, /*object*/ element)
, where index is the index in the jQuery set of the element in question, and element is a reference to that element. In addition,
the this variable is set to point to the same element (see this example). An example that sets and gets the height and inner height:
<div id="d0" style="height:700px;padding:7px;">
jQuery is a fast, small, and feature-rich JavaScript library.
</div>
<script>
var $d0 = jQuery("#d0");
var height = $d0.height();
console.log(height); // 700
var innerHeight = $d0.innerHeight();
console.log(innerHeight); // 714
</script>
This method returns or sets the computed outer height, i.e.
the value that is current at any time. The value returned (or set) with this method represents the height of the element including padding and border, but without any margin (see diagram).
To get the outer height in pixels: var outerHeight = jQuerySet.outerHeight([withMargin])
. This returns the outer height as a number (in pixels), optionally including the margin. To set outer height use: jQuerySet.outerHeight(value)
. The value can be a number, which jQuery then
takes to be pixels. If you want to define the outer height in another unit, pass a string with the type of unit appended, e.g. "200em". The value may also be a function, which is then expected to return the new value for the outer height. The function must have the
signature function(/*integer*/ index, /*object*/ element)
, where index is the index in the jQuery set of the element in question, and element is a reference to that element. In addition,
the this variable is set to point to the same element (see this example). In the next example, height, outer height and outer height including margin
are obtained. After increasing the outer height by 20 px, the same properties are queried again:
<div id="d0" style="height:700px;padding:7px;border:3px solid;margin:2px;">
jQuery is a fast, small, and feature-rich JavaScript library.
</div>
<script>
var $d0 = jQuery("#d0");
var height = $d0.height();
console.log(height); // 700
var outerHeight = $d0.outerHeight(true);
console.log(outerHeight); // 724
outerHeight = $d0.outerHeight();
console.log(outerheight); // 720
$d0.outerHeight(740); // Increase outer height by 20 px
height = $d0.height();
console.log(height); // 720
outerHeight = $d0.outerHeight(true);
console.log(outerHeight); // 744
outerheight = $d0.outerHeight();
console.log(outerHeight); // 740
</script>
This method gets or sets the values in pixels for element left and top relative to the document left and top. The position is defined in terms of an object with numeric
left and top properties. To retrieve the position use var offset = jQuerySet.offset()
. To set the position use jQuerySet.offset(position)
. When setting the position, it is also possible to use a function, which is then invoked for each element in the jQuery set. The function must have the
signature function(/*integer*/ index, /*object*/ element)
, where index is the index in the jQuery set of the element in question, and element is a reference to that element. In addition,
the this variable is set to point to the same element (see this example).
An example that moves an element 100 pixels to the right:
<body style="left:8px;top:8px;">
<script src="jquery-2.1.4.js"></script>
<div id="d0">jQuery</div>
<div id="d1">jQuery</div>
<script>
var $d1 = jQuery("#d1");
var position = $d1.offset();
console.log(position); // Object { top=28, left=8}
$d1.offset(
{
left: position.left + 100,
top: position.top,
});
position = $d1.offset();
console.log(position); // Object { top=28, left=108}
</script>
</body>
Note that setting position with the offset method implicitly sets the style.position to relative. This is demonstrated by the example below, which is functionally equivalent to the above.
<body style="left:8px;top:8px;">
<script src="jquery-2.1.4.js"></script>
<div id="d0">jQuery</div>
<div id="d1">jQuery</div>
<script>
var $d1 = jQuery("#d1");
var position = $d1.offset();
console.log(position); // Object { top=28, left=8}
var d1 = $d1[0];
d1.style.position = "relative";
d1.style.left = "100px";
d1.style.top = "0px";
position = $d1.offset();
console.log(position); // Object { top=28, left=108}
</script>
</body>
This method gets the values in pixels for element left and top relative to the offset parent, which is the nearest ancestor with style.position equal to
relative, absolute or fixed. The position is defined in terms of an object with numeric
left and top properties. To retrieve the position use var position = jQuerySet.position()
.
An example that gets the position of an element:
<div id="d0" style="position:relative;left:100px;top:100px;">
<div id="d1" style="height:20px;">jQuery</div>
<div id="d2" style="height:20px;">jQuery</div>
<div id="d3" style="height:20px;">jQuery</div>
</div>
<script>
var $d3 = jQuery("#d3");
var position = $d3.position();
console.log(position); // Object { top=40, left=0}
</script>
This method gets or sets the values in pixels for the position of the vertical scroll bar of the elements in the jQuery set. To retrieve the scroll bar position use var scrollTop = jQuerySet.scrollTop()
and
to set it use jQuerySet.scrollTop(/*integer*/ value)
.
An example:
<div id="d0" style="width:200px;height:200px;overflow:scroll;">
jQuery is a fast, small, and feature-rich JavaScript library. It makes things
like HTML document traversal and manipulation, event handling, animation, and
Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
With a combination of versatility and extensibility, jQuery has changed the way
that millions of people write JavaScript.
</div>
<script>
var $d0 = jQuery("#d0");
var scrollTop = $d0.scrollTop();
console.log(scrollTop); // 0
$d0.scrollTop(80);
scrollTop = $d0.scrollTop();
console.log(scrollTop); // 80
</script>
This method gets or sets the values in pixels for the position of the horizontal scroll bar of the elements in the jQuery set. To retrieve the scroll bar position use var scrollTop = jQuerySet.scrollLeft()
and
to set it use jQuerySet.scrollLeft(/*integer*/ value)
.
See the scrollTop method for an example.
This method gets or sets the inner html of the elements in the jQuery set. To retrieve the inner html of the first element in the set, use var innerHtml = jQuerySet.html()
and
to set it for all elements in the set, use jQuerySet.html(/*string or function*/ value)
. Instead of passing a string for the value, it is also possible to specify a function of the
format function(/*integer*/ index, /*string*/ currentHtml)
returning a string where the this
variable will be set to reference the element in question.
The following example replaces the inner html of an element:
<div id="d0">
<span>span</span>
</div>
<script>
var $d0 = jQuery("#d0");
$d0.html("Laurel & Hardy
");
var innerHtml = $d0.html();
console.log(innerHtml); // Laurel & Hardy
// displayed : Laurel & Hardy
</script>
This method gets or sets the content of the elements in the jQuery set. To retrieve the combined text content of the elements in the set, use var text = jQuerySet.text()
and
to set it for all elements in the set, use jQuerySet.text(/*string or function*/ value)
. Any characters with special meaning in html, such as angle brackets,
will be escaped. Instead of passing a string for the value, it is also possible to specify a function of the
format function(/*integer*/ index, /*string*/ currentText)
returning a string where the this
variable will be set to reference the element in question.
Note that setting element content with this function wipes all preexisting content, including child elements.
The following example replaces the content of two elements:
<div id="d0">div0
<span>span0</span>
</div>
<div id="d1">div1</div>
<script>
var $divs = jQuery("div");
var text = $divs.text();
console.log(text); /* div0
span0
div1 */
$divs.text("2x + 1 < 3");
text = $divs.text();
console.log(text); // 2x + 1 < 32x + 1 < 3
</script>
The append method is quite a versatile means of creating or moving elements, depending on how it is used. In any case, elements are appended to the existing content of the elements in the jQuery set. Also, any source elements are removed (does not apply to the cases of passing html or a function for the parameter, since there are no source elements in those cases). The method accepts an arbitrary number of arguments (although at least one!), each being of one of these types:
function(/*integer*/ index, /*string*/ currentContent)
returning a string where the this
variable will be set to reference the element in question.A simple example that moves an element from one element to another:
<div id="outer">
<div id="d0">
<span id="s0">span0</span>
</div>
<div id="d1">DIV1</div>
</div>
<script>
var $d1 = jQuery("#d1");
var $s0 = jQuery("#s0");
$d1.append($s0); // Move s0 from d0 to d1
var html = jQuery("#outer").html();
console.log(html);
/*
<div id="d0">
</div>
<div id="d1">DIV1<span id="s0">span0</span></div>
*/
</script>
The next example illustrates passing multiple arguments, namely a jQuery set and an array of elements.
<div id="outer">
<span>span0</span>
<span>span1</span>
<p></p>
<div id="d0"></div>
<div id="d1"></div>
</div>
<script>
var $d1 = jQuery("div>div");
var p = document.getElementsByTagName("p");
var $spans = jQuery("span");
$d1.append($spans, p); // Move 2 span and 1 p to d0 and d1
var html = jQuery("#outer").html();
console.log(html);
/*
<div id="d0"><span>span0</span><span>span1</span><p></p></div>
<div id="d1"><span>span0</span><span>span1</span><p></p></div>
*/
</script>
The next example illustrates using a function to add content to elements.
<div id="outer">
<div id="d0">div0</div>
<div id="d1">div1</div>
</div>
<script>
var $d1 = jQuery("div>div");
$d1.append(function (/*integer*/ index, /*string*/ currentInnerHtml)
{
return " UPDATED";
}
);
var html = jQuery("#outer").html();
console.log(html);
/*
<div id="d0">div0 UPDATED</div>
<div id="d1">div1 UPDATED</div>
*/
</script>
The prepend method is the mirror image of the append method, prepending to the existing content, rather than appending. Element contents are added before the existing content of the elements in the jQuery set. Also, any source elements are removed (does not apply to the cases of passing html or a function for the parameter, since there are no source elements in those cases). The method accepts an arbitrary number of arguments (although at least one!), each being of one of these types:
function(/*integer*/ index, /*string*/ currentContent)
returning a string where the this
variable will be set to reference the element in question.
A simple example that moves an element from one element to another (contrast this with the equivalent example for the append method):
<div id="outer">
<div id="d0">
<span id="s0">span0</span>
</div>
<div id="d1">DIV1</div>
</div>
<script>
var $d1 = jQuery("#d1");
var $s0 = jQuery("#s0");
$d1.prepend($s0); // Move s0 from d0 to d1
var html = jQuery("#outer").html();
console.log(html);
/*
<div id="d0">
</div>
<div id="d1"><span id="s0">span0</span>DIV1</div>
*/
</script>
While the append method moves elements to inside target nodes, the after method moves elements to a position just after the target element(s). Any source elements are removed (does not apply to the cases of passing html or a function for the parameter, since there are no source elements in those cases). The method accepts an arbitrary number of arguments (although at least one!), each being of one of these types:
function(/*integer*/ index, /*string*/ currentContent)
returning a string where the this
variable will be set to reference the element in question.
A simple example that moves an element to positions after the target elements:
<div id="outer">
<div id="d0">
<span id="s0">span0</span>
</div>
<div id="d1"></div>
<div id="d2"></div>
</div>
<script>
var $d1d2 = jQuery("#d1,#d2");
var $s0 = jQuery("#s0");
$d1d2.after($s0); // Move s0 from d0 to after d1 / d2
var html = jQuery("#outer").html();
console.log(html);
/*
<div id="d0">
</div>
<div id="d1"></div><span id="s0">span0</span>
<div id="d2"></div><span id="s0">span0</span>
*/
</script>
While the prepend method moves elements to inside target nodes, the before method moves elements to a position just before the target element(s). Any source elements are removed (does not apply to the cases of passing html or a function for the parameter, since there are no source elements in those cases). The method accepts an arbitrary number of arguments (although at least one!), each being of one of these types:
function(/*integer*/ index, /*string*/ currentContent)
returning a string where the this
variable will be set to reference the element in question.
A simple example that moves an element to positions before the target elements:
<div id="outer">
<div id="d0">
<span id="s0">span0</span>
</div>
<div id="d1"></div>
<div id="d2"></div>
</div>
<script>
var $d1d2 = jQuery("#d1,#d2");
var $s0 = jQuery("#s0");
$d1d2.before($s0); // Move s0 from d0 to before d1 / d2
var html = jQuery("#outer").html();
console.log(html);
/*
<div id="d0">
</div>
<span id="s0">span0</span><div id="d1"></div>
<span id="s0">span0</span><div id="d2"></div>
*/
</script>
This method is in one way the opposite of the append method in that source and target are reversed. With the appendTo method, source elements are the elements contained in the jQuery set that the method is called on. The source elements are appended to the existing content of the elements specified in the argument. Also, any source elements are removed (does not apply to the cases of passing html or a function for the parameter, since there are no source elements in those cases). The method accepts an arbitrary number of arguments (although at least one!), each being of one of these types:
A simple example that moves an element to inside two other elements:
<div id="outer">
<div id="d0">
<span id="s0">span0</span>
</div>
<div id="d1">DIV1</div>
<div id="d2">DIV2</div>
</div>
<script>
var $d1d2 = jQuery("#d1,#d2");
var $s0 = jQuery("#s0");
$s0.appendTo($d1d2); // Move s0 from d0 to after existing content of d1 / d2
var html = jQuery("#outer").html();
console.log(html);
/*
<div id="d0">
</div>
<div id="d1">DIV1<span id="s0">span0</span></div>
<div id="d2">DIV2<span id="s0">span0</span></div>
*/
</script>
This method is in one way the opposite of the prepend method in that source and target are reversed. With the prependTo method, source elements are the elements contained in the jQuery set that the method is called on. The source elements are prepended to the existing content of the elements specified in the argument. Also, any source elements are removed (does not apply to the cases of passing html or a function for the parameter, since there are no source elements in those cases). The method accepts an arbitrary number of arguments (although at least one!), each being of one of these types:
A simple example that moves an element to inside two other elements:
<div id="outer">
<div id="d0">
<span id="s0">span0</span>
</div>
<div id="d1">DIV1</div>
<div id="d2">DIV2</div>
</div>
<script>
var $s0 = jQuery("#s0");
$s0.prependTo("#d1,#d2"); // Move s0 from d0 to before existing content of d1 / d2
var html = jQuery("#outer").html();
console.log(html);
/*
<div id="d0">
</div>
<div id="d1"><span id="s0">span0</span>DIV1</div>
<div id="d2"><span id="s0">span0</span>DIV2</div>
*/
</script>
This method is in one way the opposite of the after method in that source and target are reversed. With the insertAfter method, source elements are the elements contained in the jQuery set that the method is called on. The source elements are appended after the elements specified in the argument. Also, any source elements are removed (does not apply to the cases of passing html or a function for the parameter, since there are no source elements in those cases). The method accepts an arbitrary number of arguments (although at least one!), each being of one of these types:
A simple example that moves two elements to a position after another element:
<div id="outer">
<div id="d0">
<span>span0</span>
<span>span1</span>
</div>
<div id="d1"></div>
</div>
<script>
var $spans = jQuery("span");
$spans.insertAfter("#d1"); // Move span nodes from d0 to after d1
var html = jQuery("#outer").html();
console.log(html);
/*
<div id="d0">
</div>
<div id="d1"></div><span>span0</span><span>span1</span>
*/
</script>
This method is in one way the opposite of the before method in that source and target are reversed. With the insertBefore method, source elements are the elements contained in the jQuery set that the method is called on. The source elements are prepended before the elements specified in the argument. Also, any source elements are removed (does not apply to the cases of passing html or a function for the parameter, since there are no source elements in those cases). The method accepts an arbitrary number of arguments (although at least one!), each being of one of these types:
A simple example that moves two elements to a position before another element:
<div id="outer">
<div id="d0">
<span>span0</span>
<span>span1</span>
</div>
<div id="d1"></div>
</div>
<script>
var $spans = jQuery("span");
$spans.insertBefore("#d1"); // Move span nodes from d0 to before d1
var html = jQuery("#outer").html();
console.log(html);
/*<div id="d0">
</div>
<span>span0</span><span>span1</span><div id="d1"></div>
*/
</script>
The wrap method is defined as jQuerySet.wrap(wrapIn)
and returns this
. This method wraps existing elements inside elements that are
either created from scratch or cloned from existing elements. The elements contained in the jQuery set that the method is called
on will be wrapped by copies of the element specified in the argument. A variety of types can be passed as argument to specify the element to serve as template for wrapping elements:
function(/*integer*/ index)
, where the this
variable will be set to reference the element in question.A simple example that wraps two elements in a copy of an existing element:
<div id="outer">
<span>span0</span>
<span>span1</span>
<p>P0</p>
<p>P1</p>
</div>
<script>
var $spans = jQuery("span");
var $p = jQuery("p")
$spans.wrap($p); // Wrap span nodes in clones of first p
var html = jQuery("#outer").html();
console.log(html);
/*
<p>P0<span>span0</span></p>
<p>P0<span>span1</span></p>
<p>P0</p>
<p>P1</p>
*/
</script>
An example of using a function to specify the markup of the wrapping element:
<div id="outer">
<span>span0</span>
<span>span1</span>
</div>
<script>
var $spans = jQuery("span");
$spans.wrap(function (index)
{
return "NEW DIV #" + index + "";
}
);
var html = jQuery("#outer").html();
console.log(html);
/*
<div>NEW DIV #0<span>span0</span></div>
<div>NEW DIV #1<span>span1</span></div>
*/
</script>
An example of using a query expression (not recommended!) to specify the wrapping element:
<div id="outer">
<span>span0</span>
<span>span1</span>
<p>P0</p>
<p>P1</p>
</div>
<script>
var $spans = jQuery("span");
$spans.wrap("p:first"); // Use first p element as template
var html = jQuery("#outer").html();
console.log(html);
/*
<p>P0<span>span0</span></p> (1)
<p>P0<span>span0<span>span1</span></span></p> (2)
<p>P0</p> (3)
<p>P1</p> (4)
*/
</script>
By specifying the query expression p:first
one would think that the first p element would serve as template for wrapping both span elements. But it seems
that the query expression is reevaluated for each element. In the above example, the newly created p element (1) gets to serve as template for wrapping the next span element (2). This is
hardly what one would want.
The wrapAll method is defined as jQuerySet.wrapAll(wrapIn)
and returns this
. This method wraps existing elements inside one element that is
either created from scratch or cloned from an existing element. The elements contained in the jQuery set that the method is called
on will be wrapped by a copy of the element specified in the argument. A variety of types can be passed as argument to specify the element to serve as template for wrapping elements:
A simple example that wraps two elements in a new paragraph element:
<div id="outer">
<span id="s0">span0</span>
<span id="s1">span1</span>
<span id="s2">span2</span>
</div>
<script>
var $s0s2 = jQuery("#s0,#s2");
$s0s2.wrapAll(""
);
var html = jQuery("#outer").html();
console.log(html);
/*
<p><span id="s0">span0</span><span id="s2">span2</span></p>
<span id="s1">span1</span>
*/
</script>
The wrapInner method is defined as jQuerySet.wrapInner(wrapIn)
and returns this
. Whereas the wrap method
wraps the entire element, this method wraps only the element contents, including child elements. This method wraps element content inside elements that are
either created from scratch or cloned from existing elements. The contents of elements contained in the jQuery set that the method is called
on will be wrapped by copies of the element specified in the argument. A variety of types can be passed as argument to specify the element to serve as template for wrapping elements:
function(/*integer*/ index)
, where the this
variable will be set to reference the element in question.
A simple example that wraps the contents of two elements in new span elements:
<div id="outer">
<p id="p0">p0<a>Anchor</a></p>
<p id="p1">p1</p>
<p id="p2">p2</p>
</div>
<script>
var $p0p2 = jQuery("#p0,#p2");
$p0p2.wrapInner("");
var html = jQuery("#outer").html();
console.log(html);
/*
<p id="p0"><span>p0<a>Anchor</a></span></p>
<p id="p1">p1</p>
<p id="p2"><span>p2</span></p>
*/
</script>
The unwrap method removes the parent elements containing the elements contained in the jQuery set. All content in the removed nodes is preserved.
A simple example that removes the parent nodes of span elements:
<div id="outer">
<p id="p0">p0 <span>span0</span> <span>span1</span> <a>anchor</a> </p>
<p id="p1">p1 <span>span2</span> </p>
<p id="p2">p2</p>
</div>
<script>
var $span = jQuery("span");
$span.unwrap(); // remove parent nodes of span elements
var html = jQuery("#outer").html();
console.log(html);
/*
p0<span>span0</span><span>span1</span><a>anchor</a>
p1<span>span2</span>
<p id="p2">p2</p>
*/
</script>
The detach method removes elements from the DOM. However, the elements, together with child nodes, data, event handlers and everything, are still held in the jQuery set after removal. A common scenario where this functionality comes in handy is when you remove elements from the
DOM, apply changes to them and then put them back in. If you are going to apply changes to a lot of elements, this is likely to perform better (and appear better to the user), because the browser will not have to refresh things on each tiny update. The method
has the signature jQuerySet.detach([selector])
and returns a reference to the same jQuery set. The selector argument takes a jQuery expression that allows one to further filter exactly which elements will be detached.
An example that removes an element, applies an update and reinserts it at a different location:
<div id="outer">
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
</div>
<script>
var $p = jQuery("#p1");
$p.detach(); // remove p1
var html = jQuery("#outer").html();
console.log(html); /*
<p id="p0"></p>
<p id="p2"></p>
*/
$p.width(200);
$p.insertAfter("#p2"); // reinsert it a a different place
html = jQuery("#outer").html();
console.log(html); /*<p id="p0"></p>
<p id="p2"></p><p style="width: 200px;" id="p1"></p>
*/
</script>
The remove method removes elements from the DOM. After removal, the elements are still held in the jQuery set and can be reinserted to the document, but event handlers and any data are gone. Contrast this with the
detach method. The remove method
has the signature jQuerySet.remove([selector])
and returns a reference to the same jQuery set. The selector argument takes a jQuery expression that allows one to further filter exactly which elements will be removed.
An example that removes an element and reinserts it at a different location:
<div id="outer">
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
</div>
<script>
var $p = jQuery("#p1");
$p.data("custom", 0); //add some data
$p.remove(); // remove p1
var html = jQuery("#outer").html();
console.log(html); /*
<p id="p0"></p>
<p id="p2"></p>
*/
$p.insertAfter("#p2"); // reinsert it a a different place
var data = $p.data("custom");
console.log(data); // undefined
html = jQuery("#outer").html();
console.log(html); /*<p id="p0"></p>
<p id="p2"></p><p id="p1"></p>
*/
</script>
The empty method removes contents, including child nodes, from elements. The empty method
has the signature jQuerySet.empty()
and returns a reference to the same jQuery set.
An example that removes element content:
<div id="outer">
<p id="p0"> P0 TEXT <span>More text</span></p>
</div>
<script>
var $p = jQuery("#p0");
$p.empty(); // empty p0
var html = jQuery("#outer").html();
console.log(html); // <p id="p0"></p>
</script>
The clone method copies elements from the DOM. The method performs a deep cloning, in that the entire subtrees of elements are copied. After cloning, the new elements can be inserted into the document using a method such as the appendTo method. The clone method
has the signature jQuerySet.clone([/*boolean*/ copyEventHandlersAndData[, /*boolean*/ copyChildrenEventHandlersAndData]])
and returns a reference to a new jQuery set containing the cloned elements.
The first parameter specifies if event handlers and data attached to the elements in the jQuery set are to be copied, and the second parameter specifies the same thing for child elements.
The behaviour of the two parameters is a bit counterintuitive. The table below summarizes whether data and event handlers are preserved in the cloned elements (column Element) and their children (column Children), depending on whether you pass true or false for the two arguments or omit a value alltogether (void):
Params | Element | Children |
void, void | No | No |
false, void | No | No |
false, false | No | No |
false, true | No | No |
true, void | Yes | Yes |
true, false | Yes | No |
true, true | Yes | Yes |
An example that clones an element and inserts the new element:
<div id="outer">
<div><span>TEXT</span></div>
</div>
<script>
var $div = jQuery("#outer div");
var $newDiv = $div.clone(true); // Clone inner div
$newDiv.appendTo($div.parent());
var html = jQuery("#outer").html();
console.log(html);
/*
<div><span>TEXT</span></div>
<div><span>TEXT</span></div>
*/
The replaceWith method removes elements from the DOM and inserts them in another place in place of existing content. Contrast this with the append method. It can also be used to create entirely new content instead of
moving existing elements. The method
has the signature jQuerySet.replaceWith(content)
and returns a reference to a new jQuery set containing the elements that were replaced. The single parameter can take the following types:
function(/*integer*/ index, /*string*/ currentContent)
, where the this
variable will be set to reference the element to be replaced. The index parameter contains the index of the element in the jQuery set, and the currentContent parameter contains the inner html of the same element.
In all cases, the elements that the method is called on are removed.
An example that uses a function to change the node name of an element:
<div id="outer">
<div id="d0"><span>TEXT</span></div>
</div>
<div id="d1"><span>OTHER TEXT</span></div>
<script>
var $div = jQuery("#outer div");
// change the tag name of #d0 from div to p:
$div.replaceWith(function (/*integer*/ index, /*string*/ currentContent)
{
return ""
+ currentContent + "";
});
var html = jQuery("#outer").html();
console.log(html); // <p id="d0"><span>OTHER TEXT</span></p>
</script>
The replaceAll method removes elements from the DOM and inserts them in another place in place of existing content. This method is the mirror image of the replaceWith method in that source and target are
reversed - with the replaceAll method the elements to be replaced are specified in the single argument. The method
has the signature jQuerySet.replaceAll(target)
and returns a reference to the jQuery set that the method was called on. The single parameter can take the following types:
In all cases, the elements defined in the argument are removed and the elements contained in the jQuery set that the method is called on are moved.
An example that uses a jQuery expression and replaces two elements:
<div id="outer">
<div>INNER DIV 0</div>
<div>INNER DIV 1</div>
</div>
<p><span>TEXT</span></p>
<p><span>SOME TEXT</span></p>
<script>
var $p = jQuery("p");
$p.replaceAll("#outer div");
var html = jQuery("#outer").html();
console.log(html);
/*
<p><span>TEXT</span></p><p><span>SOME TEXT</span></p>
<p><span>TEXT</span></p><p><span>SOME TEXT</span></p>
*/
</script>