- Manipulating Elements
- link Getting and Setting Information About Elements
- link Moving, Copying, and Removing Elements
- link Cloning Elements
- link Removing Elements
- link Creating New Elements
- .html()
- Contents:
- .html() Returns: String
- version added: 1.0 .html()
- Additional Notes:
- Example:
- Demo:
- .html( htmlString ) Returns: jQuery
- version added: 1.0 .html( htmlString )
- version added: 1.4 .html( function )
- Examples:
- How do I pull a native DOM element from a jQuery object?
- Last Updated
- Suggestions, Problems, Feedback?
- Chapters
- Books
Manipulating Elements
For complete documentation of jQuery manipulation methods, visit the Manipulation documentation on api.jquery.com.
link Getting and Setting Information About Elements
There are many ways to change an existing element. Among the most common tasks is changing the inner HTML or attribute of an element. jQuery offers simple, cross-browser methods for these sorts of manipulations. You can also get information about elements using many of the same methods in their getter incarnations. For more information on getters and setters, see the Working with Selections section. Here are a few methods you can use to get and set information about elements:
- .html() – Get or set the HTML contents.
- .text() – Get or set the text contents; HTML will be stripped.
- .attr() – Get or set the value of the provided attribute.
- .width() – Get or set the width in pixels of the first element in the selection as an integer.
- .height() – Get or set the height in pixels of the first element in the selection as an integer.
- .position() – Get an object with position information for the first element in the selection, relative to its first positioned ancestor. This is a getter only.
- .val() – Get or set the value of form elements.
Changing things about elements is trivial, but remember that the change will affect all elements in the selection. If you just want to change one element, be sure to specify that in the selection before calling a setter method.
// Changing the HTML of an element.
$( "#myDiv p:first" ).html( "New first paragraph!" );
link Moving, Copying, and Removing Elements
While there are a variety of ways to move elements around the DOM, there are generally two approaches:
- Place the selected element(s) relative to another element.
- Place an element relative to the selected element(s).
For example, jQuery provides .insertAfter() and .after() . The .insertAfter() method places the selected element(s) after the element provided as an argument. The .after() method places the element provided as an argument after the selected element. Several other methods follow this pattern: .insertBefore() and .before() , .appendTo() and .append() , and .prependTo() and .prepend() .
The method that makes the most sense will depend on what elements are selected, and whether you need to store a reference to the elements you’re adding to the page. 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. In this case, .insertAfter() , .insertBefore() , .appendTo() , and .prependTo() should be the tools of choice.
// Moving elements using different approaches.
// Make the first list item the last list item:
var li = $( "#myList li:first" ).appendTo( "#myList" );
// Another approach to the same problem:
$( "#myList" ).append( $( "#myList li:first" ) );
// Note that there's no way to access the list item
// that we moved, as this returns the list itself.
link Cloning Elements
Methods such as .appendTo() move the element, but sometimes a copy of the element is needed instead. In this case, use .clone() first:
// Making a copy of an element.
// Copy the first list item to the end of the list:
$( "#myList li:first" ).clone().appendTo( "#myList" );
If you need to copy related data and events, be sure to pass true as an argument to .clone() .
link Removing Elements
There are two ways to remove elements from the page: .remove() and .detach() . Use .remove() when you want to permanently remove the selection from the page. While .remove() 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.
Use .detach() if you need the data and events to persist. Like .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.
The .detach() method is extremely valuable if you are doing heavy manipulation on an element. In that case, it’s beneficial to .detach() the element from the page, work on it in your code, then restore it to the page when you’re done. This limits expensive «DOM touches» while maintaining the element’s data and events.
If you want to leave the element on the page but remove its contents, you can use .empty() to dispose of the element’s inner HTML.
link Creating New Elements
jQuery offers a trivial and elegant way to create new elements using the same $() method used to make selections:
// Creating a new element with an attribute object.
$( "",
html: "This is a new link",
"class": "new",
href: "foo.html"
>);
Note that the attributes object in the second argument above, the property name class is quoted, although the property names html and href are not. Property names generally do not need to be quoted unless they are reserved words (as class is in this case).
When you create a new element, it is not immediately added to the page. There are several ways to add an element to the page once it's been created.
// Getting a new element on to the page.
var myNewElement = $( "
New element
" );myNewElement.appendTo( "#content" );
myNewElement.insertAfter( "ul:last" ); // This will remove the p from #content!
$( "ul" ).last().after( myNewElement.clone() ); // Clone the p so now we have two.
The created element doesn't need to be stored in a variable – you can call the method to add the element to the page directly after the $() . However, most of the time you'll want a reference to the element you added so you won't have to select it later.
You can also 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:
The syntax for adding new elements to the page is easy, so it's tempting to forget that there's a huge performance cost for adding to the DOM repeatedly. If you're 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. Use an array to gather all the pieces together, then join them into a single string for appending:
.html()
Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
Contents:
.html() Returns: String
Description: Get the HTML contents of the first element in the set of matched elements.
version added: 1.0 .html()
This method is not available on XML documents.
In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned. Consider this code:
In order for the following 's content to be retrieved, it would have to be the first one with class="demo-container" in the document:
div class="demo-container">
div class="demo-box">Demonstration Box div>
div>
The result would look like this:
div class="demo-box">Demonstration Box div>
This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.
Additional Notes:
- By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, ). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.
Example:
Click a paragraph to convert it from html to text.
html>
html lang="en">
head>
meta charset="utf-8">
title>html demo title>
style>
p
margin: 8px;
font-size: 20px;
color: blue;
cursor: pointer;
>
b
text-decoration: underline;
>
button
cursor: pointer;
>
style>
script src="https://code.jquery.com/jquery-3.7.0.js"> script>
head>
body>
p>
b>Click b> to change the span id="tag">html span>
p>
p>
to a span id="text">text span> node.
p>
p>
This button name="nada">button button> does nothing.
p>
script>
$( "p" ).on( "click", function( )
var htmlString = $( this ).html();
$( this ).text( htmlString );
>);
script>
body>
html>
Demo:
.html( htmlString ) Returns: jQuery
Description: Set the HTML contents of each element in the set of matched elements.
version added: 1.0 .html( htmlString )
version added: 1.4 .html( function )
A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.
The .html() method is not available in XML documents.
When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.
Consider the following HTML:
div class="demo-container">
div class="demo-box">Demonstration Box div>
div>
The content of can be set like this:
$( "div.demo-container" )
.html( "
All new content. You bet!
" );
That line of code will replace everything inside :
div class="demo-container">
p>All new content. em>You bet! em> p>
div>
As of jQuery 1.4, the .html() method allows the HTML content to be set by passing in a function.
$( "div.demo-container" ).html(function( )
var emphasis = "" + $( "p" ).length + " paragraphs!";
return "
All new content for "
+ emphasis + "";>);
Given a document with six paragraphs, this example will set the HTML of to
All new content for 6 paragraphs!
.
This method uses the browser's innerHTML property. Some browsers may not generate a DOM that exactly replicates the HTML source provided. For example, Internet Explorer prior to version 8 will convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.
To set the content of a element, which does not contain HTML, use the .text() method and not .html() .
Note: In Internet Explorer up to and including version 9, setting the text content of an HTML element may corrupt the text nodes of its children that are being removed from the document as a result of the operation. If you are keeping references to these DOM elements and need them to be unchanged, use .empty().html( string ) instead of .html(string) so that the elements are removed from the document before the new string is assigned to the element.
Examples:
Add some html to each div.
How do I pull a native DOM element from a jQuery object?
A jQuery object is an array-like wrapper around one or more DOM elements. To get a reference to the actual DOM elements (instead of the jQuery object), you have two options. The first (and fastest) method is to use array notation:
$( "#foo" )[ 0 ]; // Equivalent to document.getElementById( "foo" )
The second method is to use the .get() function:
$( "#foo" ).get( 0 ); // Identical to above, only slower.
You can also call .get() without any arguments to retrieve a true array of DOM elements.
Last Updated
Suggestions, Problems, Feedback?
Chapters
Books
Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath