- Вставьте HTML в div с помощью JavaScript/jQuery
- 1. Использование jQuery
- JS
- HTML
- JS
- HTML
- 2. Использование JavaScript
- JS
- HTML
- JS
- HTML
- JS
- HTML
- .append()
- .append( content [, content ] ) Returns: jQuery
- version added: 1.0 .append( content [, content ] )
- version added: 1.4 .append( function )
- Additional Arguments
- Additional Notes:
- Examples:
- .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:
- Как с помощью js добавить html код в div. HTML в Div через JavaScript или jQuery.
Вставьте HTML в div с помощью JavaScript/jQuery
В этом посте мы обсудим, как вставить HTML в div в JavaScript и jQuery.
1. Использование jQuery
С помощью jQuery вы можете использовать .append() метод для вставки указанного HTML в качестве последнего дочернего элемента контейнера div.
JS
HTML
Чтобы вставить указанное содержимое в качестве первого дочернего элемента контейнера div, рассмотрите возможность использования .prepend() метод вместо этого.
JS
HTML
2. Использование JavaScript
В простом JavaScript innerHTML Свойство часто используется для замены содержимого элемента. Чтобы вставить HTML в контейнер, а не заменять все его содержимое, вы можете использовать += оператора, как показано ниже:
JS
HTML
Вместо прямого изменения innerHTML , вы должны использовать appendChild() метод.
JS
HTML
Кроме того, в JavaScript есть нативный метод insertAdjacentHTML() для вставки HTML в документ. Он принимает позицию относительно элемента, которая может быть:
- ‘beforebegin’ : Перед самим элементом.
- ‘afterbegin’ : прямо внутри элемента, перед его первым дочерним элементом.
- ‘beforeend’ : Сразу внутри элемента, после его последнего дочернего элемента.
- ‘afterend’ : после самого элемента.
JS
HTML
Вот и все, что касается вставки HTML в div в JavaScript и jQuery.
Средний рейтинг 4.69 /5. Подсчет голосов: 32
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂
Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно
.append()
.append( content [, content ] ) Returns: jQuery
Description: Insert content, specified by the parameter, to the end of each element in the set of matched elements.
version added: 1.0 .append( content [, content ] )
DOM element, text node, array of elements and text nodes, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.
version added: 1.4 .append( function )
A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.
The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend() ).
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>
You 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>
You 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):
div class="container">
div class="inner">Hello div>
div class="inner">Goodbye div>
h2>Greetings h2>
div>
Important: If there is more than one target element, however, cloned copies of the inserted element will be created for each target except for the last one.
Additional Arguments
Similar to other content-adding methods such as .prepend() and .before() , .append() also supports passing in multiple arguments as input. Supported input includes DOM elements, jQuery objects, HTML strings, and arrays of DOM elements.
For example, the following will insert two new s and an existing as the last three child nodes of the body:
Выше текст добавленный на чистом JavaScriptvar $newdiv1 = $( "
newdiv2 = document.createElement( "div" ),
existingdiv1 = document.getElementById( "foo" );
$( "body" ).append( $newdiv1, [ newdiv2, existingdiv1 ] );
Since .append() can accept any number of additional arguments, the same result can be achieved by passing in the three s as three separate arguments, like so: $('body').append( $newdiv1, newdiv2, existingdiv1 ) . The type and number of arguments will largely depend on how you collect the elements in your code.
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 .
Examples:
Appends some HTML to all paragraphs.
.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.
Как с помощью js добавить html код в div. HTML в Div через JavaScript или jQuery.
Добавить можно, естественно, не только в DIV элемент на сайте, но и совершенно в любую другую конструкцию вашего HTML сайта.
В примере будет рассмотрено 2 варианта вставки текста в html с помощью javascript и дополнительно вариант вставки кода через функцию, которая запускается по нажатию на кнопку.
1. На чистом JavaScript без jQuery
Пример HTML - текст будет добавлен в тег с классом demo
id="description_id"> class="demo">
Пример CSS (для моего примера не более)
#description_id padding: 50px 0; font-family: roboto, arial; > p font-weight: 600; >
Код JavaScript без jQuery
2. На JavaScript используя библиотеку jQuery
Пример HTML - текст будет добавлен в тег с классом description_class
id="description_id"> class="description_class">