-
jQuery( String html ) returns jQuery
Create DOM elements on-the-fly from the provided String of raw HTML.
You can pass in plain HTML Strings written by hand, create them using some template engine or plugin, or load them via AJAX. There are limitations when creating input elements, see the second example. Also when passing strings that may include slashes (such as an image path), escape the slashes. When creating single elements use the closing tag or XHTML format. For example, to create a span use $("<span/>") or $("<span></span>") instead of without the closing slash/tag.Example:
Creates a div element (and all of its contents) dynamically, and appends it to the body element. Internally, an element is created and its innerHTML property set to the given markup. It is therefore both quite flexible and limited.
$("<div><p>Hello</p></div>").appendTo("body")Example:
Do not create <input>-Elements without a type-attribute, due to Microsofts read/write-once-rule for the type-attribute of <input>-elements, see this [http://msdn2.microsoft.com/en-us/library/ms534700.aspx official statement] for details.
// Does NOT work in IE: $("<input/>").attr("type", "checkbox"); // Does work in IE: $("<input type='checkbox'/>"); -
jQuery( Element, Array<Element> elements ) returns jQuery
Wrap jQuery functionality around a single or multiple DOM Element(s).
This function also accepts XML Documents and Window objects as valid arguments (even though they are not DOM Elements).Example:
Sets the background color of the page to black.
$(document.body).css( "background", "black" );Example:
Hides all the input elements within a form.
$(myForm.elements).hide() -
jQuery( Function callback ) returns jQuery
A shorthand for $(document).ready().
Allows you to bind a function to be executed when the DOM document has finished loading. This function behaves just like $(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready to be operated on. While this function is, technically, chainable - there really isn't much use for chaining against it.
You can have as many $(document).ready events on your page as you like.
See ready(Function) for details about the ready event.Example:
Executes the function when the DOM is ready to be used.
$(function(){ // Document is ready });Example:
Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.
jQuery(function($) { // Your code using failsafe $ alias here... }); -
jQuery( String expression, Element, jQuery context ) returns jQuery
This function accepts a string containing a CSS selector which is then used to match a set of elements.
The core functionality of jQuery centers around this function. Everything in jQuery is based upon this, or uses this in some way. The most basic use of this function is to pass in an expression (usually consisting of CSS), which then finds all matching elements.
By default, if no context is specified, $() looks for DOM elements within the context of the current HTML document. If you do specify a context, such as a DOM element or jQuery object, the expression will be matched against the contents of that context.
See <a href='Selectors'>Selectors</a> for the allowed CSS syntax for expressions.Example:
Finds all p elements that are children of a div element.
$("div > p").css("border", "1px solid gray");HTML:
<p>one</p> <div><p>two</p></div> <p>three</p>Result:
[ <p>two</p> ]Example:
Finds all inputs of type radio within the first form in the document.
$("input:radio", document.forms[0]);Example:
Finds all div elements within an XML document from an AJAX response.
$("div", xml.responseXML); -
jQuery.ajax( Options options ) returns XMLHttpRequest
Load a remote page using an HTTP request.
This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks).
'''Warning: All POST are converted to GET when 'script' is the dataType.(because it loads script as a dom script tag)'''
$.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually.
'''Note:''' If you specify the dataType option described below, make sure the server sends the correct MIME type in the response (eg. xml as "text/xml"). Sending the wrong MIME type can lead to unexpected problems in your script. See <a href='Specifying_the_Data_Type_for_AJAX_Requests'>Specifying the Data Type for AJAX Requests</a> for more information.
$.ajax() takes one argument, an object of key/value pairs, that are used to initialize and handle the request. See below for a full list of the key/values that can be used.
As of jQuery 1.2, you can load JSON data located on another domain if you specify a [http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/ JSONP] callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback. Or, if you set the dataType to "jsonp" a callback will be automatically added to your Ajax request.Options
Example:
Load and execute a JavaScript file.
$.ajax({ type: "GET", url: "test.js", dataType: "script" });Example:
Save some data to the server and notify the user once its complete.
$.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", success: function(msg){ alert( "Data Saved: " + msg ); } });Example:
Retrieve the latest version of an HTML page.
$.ajax({ url: "test.html", cache: false, success: function(html){ $("#results").append(html); } });Example:
Loads data synchronously. Blocks the browser while the requests is active. It is better to block user interaction by other means when synchronization is necessary.
var html = $.ajax({ url: "some.php", async: false }).responseText;Example:
Sends an xml document as data to the server. By setting the processData option to false, the automatic conversion of data to strings is prevented.
var xmlDocument = [create xml document]; $.ajax({ url: "page.php", processData: false, data: xmlDocument, success: handleResponse }); -
jQuery.ajaxSetup( Options options ) returns
Setup global settings for AJAX requests.
See <a href='Ajax/jQuery.ajax'>$.ajax</a> for a description of all available options.Example:
Sets the defaults for AJAX requests to the url "/xmlhttp/", disables global handlers and uses POST instead of GET. The following AJAX requests then sends some data without having to set anything else.
$.ajaxSetup({ url: "/xmlhttp/", global: false, type: "POST" }); $.ajax({ data: myData }); -
jQuery.boxModel returns Boolean
States if the current page, in the user's browser, is being rendered using the [http://www.w3.org/TR/REC-CSS2/box.html W3C CSS Box Model].
Example:
Returns the box model for the iframe.
$("p").html("The box model for this iframe is: <span>" + jQuery.boxModel + "</span>");HTML:
<p> </p>Example:
Returns false if the page is in QuirksMode in Internet Explorer
$.boxModelResult:
false -
jQuery.browser returns Map
Contains flags for the useragent, read from navigator.userAgent.
Available flags are: * safari * opera * msie * mozilla
This property is available before the DOM is ready, therefore you can use it to add ready events only for certain browsers.
There are situations where object detection is not reliable enough, in such cases it makes sense to use browser detection.
A combination of browser and object detection yields quite reliable results.Example:
Show the browser info.
jQuery.each(jQuery.browser, function(i, val) { $("<div>" + i + " : <span>" + val + "</span>") .appendTo(document.body); });HTML:
<p>Browser info:</p>Example:
Returns true if the current useragent is some version of Microsoft's Internet Explorer
$.browser.msieExample:
Alerts "this is safari!" only for safari browsers
if ($.browser.safari) { alert("this is safari!"); } -
jQuery.browser.version returns String
The version number of the rendering engine for the user's browser.
Here are some typical results: * Internet Explorer: 6.0, 7.0 * Mozilla/Firefox/Flock/Camino: 1.7.12, 1.8.1.3 * Opera: 9.20 * Safari/Webkit: 312.8, 418.9Example:
Returns the browser version.
$("p").html("The browser version is: <span>" + jQuery.browser.version + "</span>");HTML:
<p> </p>Example:
Alerts the version of IE that is being used
if ( $.browser.msie ) alert( $.browser.version ); }Example:
Often you only care about the "major number," the whole number. This can be accomplished with JavaScript's built-in parseInt() function:
if (jQuery.browser.msie) { alert(parseInt(jQuery.browser.version)); } -
jQuery.data( Element elem ) returns Number
Returns a unique ID for the element.
Typically this function will only be used internally. It is called automatically when necessary when using the other data() functionality.Example:
Get the store id of an element. It is assigned on the data() function call if one hasn't been assigned yet.
$(document.body).click(function(e) { var id = jQuery.data(e.target); $("span").text(id); });HTML:
<div>A div</div> <div>Another</div> <p>The id of this div is <span>?</span></p> -
jQuery.data( Element elem, String name ) returns Any
Returns value at named data store for the element.
Example:
Get the data named "blah" stored at for an element.
$("button").click(function(e) { var adiv = $("div").get(0); var value; switch ($("button").index(this)) { case 0 : value = jQuery.data(adiv, "blah"); break; case 1 : jQuery.data(adiv, "blah", "hello"); value = "Stored!"; break; case 2 : jQuery.data(adiv, "blah", 86); value = "Stored!"; break; case 3 : jQuery.removeData(adiv); value = "Removed!"; break; } $("span").text("" + value); });HTML:
<div>A div</div> <button>Get "blah" from the div</button> <button>Set "blah" to "hello"</button> <button>Set "blah" to 86</button> <button>Remove "blah" from the div</button> <p>The "blah" value of this div is <span>?</span></p> -
jQuery.data( Element elem, String name, Any value ) returns Any
Stores the value in the named spot and also returns the value.
This function can be useful for attaching data to elements without having to create a new expando. It also isn't limited to a string. The value can be any format.
To avoid conflicts in plugins, it is usually effective to store one object using the plugin name and put all the necessary information in that object.
<code> var obj = jQuery.data($("#target").get(0), "pluginname", {}); obj[...] = ... </code>Example:
Store then retrieve a value from the div element.
var adiv = $("div").get(0); jQuery.data(adiv, "test", { first: 16, last: "pizza!" }); $("span:first").text(jQuery.data(adiv, "test").first); $("span:last").text(jQuery.data(adiv, "test").last);HTML:
<div> The values stored were <span></span> and <span></span> </div> -
jQuery.each( Object object, Function callback ) returns Object
A generic iterator function, which can be used to seamlessly iterate over both objects and arrays.
This function is not the same as $().each() - which is used to iterate, exclusively, over a jQuery object. This function can be used to iterate over anything.
The callback has two arguments:the key (objects) or index (arrays) as the first, and the value as the second.
If you wish to break the each() loop at a particular iteration you can do so by making your function return false. Other return values are ignored.Example:
Filters the original array of numbers leaving that are not 5 and have an index greater than 3. Then it removes all 9s while inverting it.
var arr = [ "one", "two", "three", "four", "five" ]; var obj = { one:1, two:2, three:3, four:4, five:5 }; jQuery.each(arr, function() { $("#" + this).text("My id is " + this + "."); return (this != "four"); // will stop running to skip "five" }); jQuery.each(obj, function(i, val) { $("#" + i).append(document.createTextNode(" - " + val)); });HTML:
<div id="one"></div> <div id="two"></div> <div id="three"></div> <div id="four"></div> <div id="five"></div>Example:
Iterates over items in an array, accessing both the current item and its index.
$.each( [0,1,2], function(i, n){ alert( "Item #" + i + ": " + n ); });Example:
Iterates over the properties in an object, accessing both the current item and its key.
$.each( { name: "John", lang: "JS" }, function(i, n){ alert( "Name: " + i + ", Value: " + n ); }); -
jQuery.extend( Object object ) returns jQuery
Extends the jQuery object itself.
Can be used to add functions into the jQuery namespace. See <a href='Core/jQuery.fn.extend'>jQuery.fn.extend</a> for more information on using this method to add <a href='Plugins/Authoring'>Plugins</a>.Example:
Adds two functions into the jQuery namespace.
jQuery.extend({ min: function(a, b) { return a < b ? a : b; }, max: function(a, b) { return a > b ? a : b; } });Result:
jQuery.min(2,3); // => 2 jQuery.max(4,5); // => 5 -
jQuery.extend( Object target, Object object1, Object objectN ) returns Object
Extend one object with one or more others, returning the original, modified, object.
This is a great utility for simple inheritance.Example:
Merge settings and options, modifying settings.
var settings = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; jQuery.extend(settings, options);Result:
settings == { validate: true, limit: 5, name: "bar" }Example:
Merge defaults and options, without modifying the defaults.
var empty = {} var defaults = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; var settings = $.extend(empty, defaults, options);Result:
settings == { validate: true, limit: 5, name: "bar" } empty == { validate: true, limit: 5, name: "bar" } -
jQuery.fn.extend( Object object ) returns jQuery
Extends the jQuery element set to provide new methods (used to make a typical jQuery plugin).
Can be used to add functions into the to add <a href='Plugins/Authoring'>plugin methods (plugins)</a>.Example:
Adds two plugin methods.
jQuery.fn.extend({ check: function() { return this.each(function() { this.checked = true; }); }, uncheck: function() { return this.each(function() { this.checked = false; }); } });Result:
$("input[@type=checkbox]").check(); $("input[@type=radio]").uncheck(); -
jQuery.get( String url, Map data, Function callback ) returns XMLHttpRequest
Load a remote page using an HTTP GET request.
This is an easy way to send a simple GET request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). If you need to have both error and success callbacks, you may want to use $.ajax.Example:
Request the test.php page, but ignore the return results.
$.get("test.php");Example:
Request the test.php page and send some additional data along (while still ignoring the return results).
$.get("test.php", { name: "John", time: "2pm" } );Example:
Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.get("test.php", function(data){ alert("Data Loaded: " + data); });Example:
Alert out the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned).
$.get("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); }); -
jQuery.getJSON( String url, Map data, Function callback ) returns XMLHttpRequest
Load JSON data using an HTTP GET request.
As of jQuery 1.2, you can load JSON data located on another domain if you specify a [http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/ JSONP] callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback.
Note: Keep in mind, that lines after this function will be executed before callback.Example:
Loads the four most recent cat pictures from the Flickr JSONP API.
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data){ $.each(data.items, function(i,item){ $("<img/>").attr("src", item.media.m).appendTo("#images"); if ( i == 3 ) return false; }); });HTML:
<div id="images"></div>Example:
Load the JSON data from test.js and access a name from the returned JSON data.
$.getJSON("test.js", function(json){ alert("JSON Data: " + json.users[3].name); });Example:
Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data.
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json){ alert("JSON Data: " + json.users[3].name); });Example:
Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.getIfModified("test.php", function(data){ alert("Data Loaded: " + data); });Example:
Alert out the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).
$.getIfModified("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });Example:
list the result of a consultation of pages,php in HTML as an array. by Manuel Gonzalez.
var id=$("#id").attr("value"); $.getJSON("pages.php",{id:id},dates); function dates(datos) { $("#list").html("Name:"+datos[1].name+"<br>"+"Last Name:"+datos[1].lastname+"<br>"+"Address:"+datos[1].address); } -
jQuery.getScript( String url, Function callback ) returns XMLHttpRequest
Loads, and executes, a local JavaScript file using an HTTP GET request.
Before jQuery 1.2, getScript was only able to load scripts from the same domain as the original page. As of 1.2, you can now load JavaScript files from any domain.
Warning: Safari 2 and older is unable to evaluate scripts in a global context synchronously. If you load functions via getScript, make sure to call them after a delay.Example:
We load the new [http://jquery.com/plugins/project/color official jQuery Color Animation plugin] dynamically and bind some color animations to occur once the new functionality is loaded.
$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){ $("#go").click(function(){ $(".block").animate( { backgroundColor: 'pink' }, 1000) .animate( { backgroundColor: 'blue' }, 1000); }); });HTML:
<button id="go">» Run</button> <div class="block"></div>Example:
Load the test.js JavaScript file and execute it.
$.getScript("test.js");Example:
Load the test.js JavaScript file and execute it, displaying an alert message when the execution is complete.
$.getScript("test.js", function(){ alert("Script loaded and executed."); }); -
jQuery.grep( Array array, Function callback, Boolean invert ) returns Array
Filter items out of an array, by using a filter function.
The specified function will be passed two arguments: The current array item and the index of the item in the array. The function must return 'true' to keep the item in the array, false to remove it.Example:
Filters the original array of numbers leaving that are not 5 and have an index greater than 3. Then it removes all 9s while inverting it.
var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ]; $("div").text(arr.join(", ")); arr = jQuery.grep(arr, function(n, i){ return (n != 5 && i > 4); }); $("p").text(arr.join(", ")); arr = jQuery.grep(arr, "a != 9"); $("span").text(arr.join(", "));HTML:
<div></div> <p></p> <span></span>Example:
Filter an array of numbers to include only numbers bigger then zero.
$.grep( [0,1,2], function(n,i){ return n > 0; });Result:
[1, 2]Example:
Filter an array of numbers to exclude numbers bigger then zero using the third parameter, invert.
$.grep( [0,1,2,3,4,5], "a > 1", true);Result:
[0, 1] -
jQuery.inArray( Any value, Array array ) returns Number
Determine the index of the first parameter in the Array (-1 if not found).
Example:
var arr = [ 4, "Pete", 8, "John" ]; $("span:eq(0)").text(jQuery.inArray("John", arr)); $("span:eq(1)").text(jQuery.inArray(4, arr)); $("span:eq(2)").text(jQuery.inArray("David", arr));HTML:
<div>"John" found at <span></span></div> <div>4 found at <span></span></div> <div>"David" found at <span></span></div> -
jQuery.isFunction( Object obj ) returns boolean
Determine if the parameter passed is a function.
Example:
Test a few parameter examples.
function stub() { } var objs = [ function () {}, { x:15, y:20 }, null, stub, "function" ]; jQuery.each(objs, function (i) { var isFunc = jQuery.isFunction(objs[i]); $("span:eq( " + i + ")").text(isFunc); });HTML:
<div>jQuery.isFunction(objs[0]) = <span></span></div> <div>jQuery.isFunction(objs[1]) = <span></span></div> <div>jQuery.isFunction(objs[2]) = <span></span></div> <div>jQuery.isFunction(objs[3]) = <span></span></div> <div>jQuery.isFunction(objs[4]) = <span></span></div>Example:
Finds out if the parameter is a funcion.
$.isFunction(function(){});Result:
true -
jQuery.makeArray( Object obj ) returns Array
Turns an array-like object into a true array.
Array-like objects have a length property and its properties are numbered from 0 to length - 1. Typically it will be unnecessary to use this function if you are using jQuery which uses this function internally.Example:
Turn a collection of HTMLElements into an Array of them.
var arr = jQuery.makeArray(document.getElementsByTagName("div")); arr.reverse(); // use an Array method on list of dom elements $(arr).appendTo(document.body);HTML:
<div>First</div> <div>Second</div> <div>Third</div> <div>Fourth</div> -
jQuery.map( Array array, Function callback ) returns Array
Translate all items in an array to another array of items.
The translation function that is provided to this method is called for each item in the array and is passed one argument: The item to be translated.
The function can then return the translated value, 'null' (to remove the item), or an array of values - which will be flattened into the full array.Example:
Maps the original array to a new one and adds 4 to each value.
var arr = [ "a", "b", "c", "d", "e" ] $("div").text(arr.join(", ")); arr = jQuery.map(arr, function(n, i){ return (n.toUpperCase() + i); }); $("p").text(arr.join(", ")); arr = jQuery.map(arr, "a + a"); $("span").text(arr.join(", "));HTML:
<div></div> <p></p> <span></span>Example:
Maps the original array to a new one and adds 4 to each value.
$.map( [0,1,2], function(n){ return n + 4; });Result:
[4, 5, 6]Example:
Maps the original array to a new one and adds 1 to each value if it is bigger then zero, otherwise it's removed.
$.map( [0,1,2], function(n){ return n > 0 ? n + 1 : null; });Result:
[2, 3]Example:
Maps the original array to a new one, each element is added with it's original value and the value plus one.
$.map( [0,1,2], function(n){ return [ n, n + 1 ]; });Result:
[0, 1, 1, 2, 2, 3]Example:
Maps the original array to a new one, each element is squared.
$.map( [0,1,2,3], "a * a" );Result:
[0, 1, 4, 9] -
jQuery.noConflict( ) returns jQuery
Run this function to give control of the $ variable back to whichever library first implemented it.
This helps to make sure that jQuery doesn't conflict with the $ object of other libraries.
By using this function, you will only be able to access jQuery using the 'jQuery' variable. For example, where you used to do $("div p"), you now must do jQuery("div p").Example:
Maps the original object that was referenced by $ back to $.
jQuery.noConflict(); // Do something with jQuery jQuery("div p").hide(); // Do something with another library's $() $("content").style.display = 'none';Example:
Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery alias inside the functions scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library.
jQuery.noConflict(); (function($) { $(function() { // more code using $ as alias to jQuery }); })(jQuery); // other code using $ as an alias to the other libraryExample:
Creates a different alias instead of jQuery to use in the rest of the script.
var j = jQuery.noConflict(); // Do something with jQuery j("div p").hide(); // Do something with another library's $() $("content").style.display = 'none'; -
jQuery.noConflict( Boolean extreme ) returns jQuery
Revert control of both the $ and jQuery variables to their original owners. '''Use with discretion.'''
This is a more-extreme version of the simple <a href='Core/jQuery.noConflict'>noConflict</a> method, as this one will completely undo what jQuery has introduced. This is to be used in an extreme case where you'd like to embed jQuery into a high-conflict environment. '''NOTE:''' It's very likely that plugins won't work after this particular method has been called.Example:
Completely move jQuery to a new namespace in another object.
var dom = {}; dom.query = jQuery.noConflict(true);Result:
// Do something with the new jQuery dom.query("div p").hide(); // Do something with another library's $() $("content").style.display = 'none'; // Do something with another version of jQuery jQuery("div > p").hide(); -
jQuery.param( Array<Elements>, jQuery, Object obj ) returns String
Serializes an array of form elements or an object (core of <a href='Ajax/serialize'>.serialize()</a> method).
Example:
Serialize a key/value object.
var params = { width:1680, height:1050 }; var str = jQuery.param(params); $("#results").text(str);HTML:
<div id="results"></div> -
jQuery.post( String url, Map data, Function callback ) returns XMLHttpRequest
Load a remote page using an HTTP POST request.
This is an easy way to send a simple POST request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). If you need to have both error and success callbacks, you may want to use $.ajax.Example:
Request the test.php page, but ignore the return results.
$.post("test.php");Example:
Request the test.php page and send some additional data along (while still ignoring the return results).
$.post("test.php", { name: "John", time: "2pm" } );Example:
Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.post("test.php", function(data){ alert("Data Loaded: " + data); });Example:
Alert out the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).
$.post("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); }); -
jQuery.removeData( Element elem ) returns
Remove the expando attribute that allows data storage on an element.
This is the complement function to jQuery.data(elem) which is called as necessary by jQuery.data(elem, name, value).Example:
Set a data store then remove it.
var adiv = $("div").get(0); $("span:eq(0)").text("" + jQuery.data(adiv, "test1")); jQuery.data(adiv, "test1", "VALUE-1"); jQuery.data(adiv, "test2", "VALUE-2"); $("span:eq(1)").text("" + jQuery.data(adiv, "test1")); jQuery.removeData(adiv); $("span:eq(2)").text("" + jQuery.data(adiv, "test1")); $("span:eq(3)").text("" + jQuery.data(adiv, "test2"));HTML:
<div>value1 before creation: <span></span></div> <div>value1 after creation: <span></span></div> <div>value1 after removal: <span></span></div> <div>value2 after removal: <span></span></div> -
jQuery.removeData( Element elem, String name ) returns
Removes just this one named data store.
This is the complement function to jQuery.data(elem, name, value).Example:
Set a data store for 2 names then remove one of them.
var adiv = $("div").get(0); $("span:eq(0)").text("" + jQuery.data(adiv, "test1")); jQuery.data(adiv, "test1", "VALUE-1"); jQuery.data(adiv, "test2", "VALUE-2"); $("span:eq(1)").text("" + jQuery.data(adiv, "test1")); jQuery.removeData(adiv, "test1"); $("span:eq(2)").text("" + jQuery.data(adiv, "test1")); $("span:eq(3)").text("" + jQuery.data(adiv, "test2"));HTML:
<div>value1 before creation: <span></span></div> <div>value1 after creation: <span></span></div> <div>value1 after removal: <span></span></div> <div>value2 after removal: <span></span></div> -
jQuery.trim( String str ) returns String
Remove the whitespace from the beginning and end of a string.
Uses a regular expression to remove whitespace from the given string.Example:
Removes the two whitespaces at the start and at the end of the string.
$("button").click(function () { var str = " lots of spaces before and after "; alert("'" + str + "'"); str = jQuery.trim(str); alert("'" + str + "' - no longer"); });HTML:
<button>Show Trim Example</button>Example:
Removes the two whitespaces at the start and at the end of the string.
$.trim(" hello, how are you? ");Result:
"hello, how are you?" -
jQuery.unique( Array array ) returns Array
Remove all duplicate elements from an array of elements.
Example:
Removes any duplicate elements from the array of divs.
var divs = $("div").get(); // add 3 elements of class dup too (they are divs) divs = divs.concat($(".dup").get()); $("div:eq(1)").text("Pre-unique there are " + divs.length + " elements."); divs = jQuery.unique(divs); $("div:eq(2)").text("Post-unique there are " + divs.length + " elements.") .css("color", "red");HTML:
<div>There are 6 divs in this document.</div> <div></div> <div class="dup"></div> <div class="dup"></div> <div class="dup"></div> <div></div>Example:
Removes any duplicate elements from the array of divs.
$.unique(document.getElementsByTagName("div"));Result:
[<div>, <div>, ...]