Adding html using jquery

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.

Читайте также:  No expression found python

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.

Источник

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

Источник

Adding html using jquery

Description: Create a new jQuery object with elements added to the set of matched elements.

version added: 1.0 .add( selector )

A string representing a selector expression to find additional elements to add to the set of matched elements.

version added: 1.0 .add( elements )

version added: 1.0 .add( html )

version added: 1.1 .add( selection )

version added: 1.4 .add( selector, context )

A string representing a selector expression to find additional elements to add to the set of matched elements.

The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method.

Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.

Do not assume that this method appends the elements to the existing collection in the order they are passed to the .add() method. When all elements are members of the same document, the resulting collection from .add() will be sorted in document order; that is, in order of each element's appearance in the document. If the collection consists of elements from different documents or ones not in any document, the sort order is undefined. To create a jQuery object with elements in a well-defined order and without sorting overhead, use the $(array_of_DOM_elements) signature.

The updated set of elements can be used in a following (chained) method, or assigned to a variable for later use. For example:

$( "p" ).add( "div" ).addClass( "widget" );
var pdiv = $( "p" ).add( "div" );

The following will not save the added elements, because the .add() method creates a new set and leaves the original set in pdiv unchanged:

var pdiv = $( "p" );
pdiv.add( "div" ); // WRONG, pdiv will not change

Consider a page with a simple list and a paragraph following it:

Источник

How to Add HTML Elements Through JQuery

jQuery, a library of JavaScript, makes numerous web programming tasks extremely easy to fulfill. Tasks that would normally take multiple lines of code to be achieved such as event handling, animations, or Ajax, can be done in just one line of code. Besides these tasks, adding HTML elements with great ease is possible using multiple methods provided in jQuery.

This guide will teach you how to add HTML elements through jQuery using several methods with the help of appropriate examples.

How to add HTML elements through jQuery

jQuery provides the following four methods to add HTML elements.

Here we have discussed all of these in detail.

append() Method

The append() method adds an element as a child within a specified element. It takes an unlimited number of new HTML elements in the form of parameters.

This method works in a way that the HTML elements are generated using either text/HTML, jQuery, or JavaScript. Afterward, those newly generated elements are appended as the last child using the append() method.

Example

Suppose you want to append new items at the end of an ordered list using the append() method. Use the following code.

HTML

In the above code, we have made a button and also created an ordered list.

jQuery

Using the jQuery append() method we will add another item to the list by clicking on the button.

Output

There were three items in the list, initially.

Suppose you click on the button thrice.

Three more items are added to the list.

prepend() Method

This method works in a similar way to that of the append() method with the only difference that instead of appending the newly created HTML elements, it will prepend the elements as the first child. It also takes an unlimited number of new HTML elements in the form of parameters.

Example

We will use the same example as above and see how the prepend() method works.

jQuery

In the above code snippet, we are using the prepend() method to add items at the start of the ordered list.

Output

Originally there were three items on the list.

Suppose you click on the button twice.

Two items are added at the start of the ordered list.

before() Method

The before() method takes an unlimited number of new HTML elements in the form of parameters. This method works in a way that the HTML elements are generated using either text/HTML, jQuery, or JavaScript and are added before an already existing element as a sibling.

Example

Suppose you want to add a heading before a paragraph by clicking on a button. This can be done using the before() method.

HTML

In the above code we have created

, and elements. Now we will use the before() method to add a heading before the paragraph.

jQuery

$ ( "p" ) . before ( "

Heading

" ) ;

Источник

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