Add html to element with jquery

Manipulating Elements

For complete documentation of jQuery manipulation methods, visit the Manipulation documentation on api.jquery.com.

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!" );

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.

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() .

Читайте также:  Привязка php к apache

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.

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:

Источник

jQuery - Add Elements

We will look at four jQuery methods that are used to add new content:

  • append() - Inserts content at the end of the selected elements
  • prepend() - Inserts content at the beginning of the selected elements
  • after() - Inserts content after the selected elements
  • before() - Inserts content before the selected elements

jQuery append() Method

The jQuery append() method inserts content AT THE END of the selected HTML elements.

Example

jQuery prepend() Method

The jQuery prepend() method inserts content AT THE BEGINNING of the selected HTML elements.

Example

Add Several New Elements With append() and prepend()

In both examples above, we have only inserted some text/HTML at the beginning/end of the selected HTML elements.

However, both the append() and prepend() methods can take an infinite number of new elements as parameters. The new elements can be generated with text/HTML (like we have done in the examples above), with jQuery, or with JavaScript code and DOM elements.

In the following example, we create several new elements. The elements are created with text/HTML, jQuery, and JavaScript/DOM. Then we append the new elements to the text with the append() method (this would have worked for prepend() too) :

Example

function appendText() <
var txt1 = "

Text.

"; // Create element with HTML
var txt2 = $(" ").text("Text."); // Create with jQuery
var txt3 = document.createElement("p"); // Create with DOM
txt3.innerHTML = "Text.";
$("body").append(txt1, txt2, txt3); // Append the new elements
>

jQuery after() and before() Methods

The jQuery after() method inserts content AFTER the selected HTML elements.

The jQuery before() method inserts content BEFORE the selected HTML elements.

Example

$("img").before("Some text before");

Add Several New Elements With after() and before()

Also, both the after() and before() methods can take an infinite number of new elements as parameters. The new elements can be generated with text/HTML (like we have done in the example above), with jQuery, or with JavaScript code and DOM elements.

In the following example, we create several new elements. The elements are created with text/HTML, jQuery, and JavaScript/DOM. Then we insert the new elements to the text with the after() method (this would have worked for before() too) :

Example

function afterText() <
var txt1 = "I "; // Create element with HTML
var txt2 = $(" ").text("love "); // Create with jQuery
var txt3 = document.createElement("b"); // Create with DOM
txt3.innerHTML = "jQuery!";
$("img").after(txt1, txt2, txt3); // Insert new elements after
>

jQuery Exercises

jQuery HTML Reference

For a complete overview of all jQuery HTML methods, please go to our jQuery HTML/CSS Reference.

Источник

.appendTo()

Description: Insert every element in the set of matched elements to the end of the target.

version added: 1.0 .appendTo( target )

A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.

The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append() , the selector expression preceding the method is the container into which the content is inserted. With .appendTo() , on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

Consider the following HTML:

h2>Greetings h2>
div class="container">
div class="inner">Hello div>
div class="inner">Goodbye div>
div>

We can create content and insert it into several elements at once:

Each inner element gets this new content:

h2>Greetings h2>
div class="container">
div class="inner">
Hello
p>Test p>
div>
div class="inner">
Goodbye
p>Test p>
div>
div>

We can also select an element on the page and insert it into another:

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned) and a new set consisting of the inserted element is returned:

div class="container">
div class="inner">Hello div>
div class="inner">Goodbye div>
h2>Greetings h2>
div>

If there is more than one target element, however, cloned copies of the inserted element will be created for each target except the last, and that new set (the original element plus clones) is returned.

Before jQuery 1.9, the append-to-single-element case did not create a new set, but instead returned the original set which made it difficult to use the .end() method reliably when being used with an unknown number of elements.

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.
  • jQuery doesn't officially support SVG. Using jQuery methods on SVG documents, unless explicitly documented for that method, might cause unexpected behaviors. Examples of methods that support SVG as of jQuery 3.0 are addClass and removeClass .

Example:

Append all spans to the element with the ID "foo" (Check append() documentation for more examples)

Источник

Оцените статью