- .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:
- .replaceWith()
- version added: 1.2 .replaceWith( newContent )
- version added: 1.4 .replaceWith( function )
- Additional Notes:
- Examples:
- .replaceWith()
- .replaceWith( newContent ) Возвращает: jQuery
- Добавлен в версии: 1.2 .replaceWith( newContent )
- Добавлен в версии: 1.4 .replaceWith( function )
- Дополнительные замечания:
.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.
.replaceWith()
Description: Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
version added: 1.2 .replaceWith( newContent )
version added: 1.4 .replaceWith( function )
The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call. Consider this DOM structure:
div class="container">
div class="inner first">Hello div>
div class="inner second">And div>
div class="inner third">Goodbye div>
div>
The second inner could be replaced with the specified HTML:
$( "div.second" ).replaceWith( "
New heading
" );
This results in the structure:
div class="container">
div class="inner first">Hello div>
h2>New heading h2>
div class="inner third">Goodbye div>
div>
All inner elements could be targeted at once:
$( "div.inner" ).replaceWith( "
New heading
" );
This causes all of them to be replaced:
div class="container">
h2>New heading h2>
h2>New heading h2>
h2>New heading h2>
div>
An element could also be selected as the replacement:
$( "div.third" ).replaceWith( $( ".first" ) );
This results in the DOM structure:
div class="container">
div class="inner second">And div>
div class="inner first">Hello div>
div>
This example demonstrates that the selected element replaces the target by being moved from its old location, not by being cloned.
The .replaceWith() method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.
Additional Notes:
- The .replaceWith() method removes all data and event handlers associated with the removed nodes.
- Prior to jQuery 1.9, .replaceWith() would attempt to add or change nodes in the current jQuery set if the first node in the set was not connected to a document, and in those cases return a new jQuery set rather than the original set. The method might or might not have returned a new result depending on the number or connectedness of its arguments! As of jQuery 1.9, .after() , .before() , and .replaceWith() always return the original unmodified set. Attempting to use these methods on a node without a parent has no effect—that is, neither the set nor the nodes it contains are changed.
Examples:
On click, replace the button with a div containing the same word.
.replaceWith()
.replaceWith( newContent ) Возвращает: jQuery
Описание: С помощью этой функции можно заменять элементы страницы новыми элементами или уже существующими.
Добавлен в версии: 1.2 .replaceWith( newContent )
Добавлен в версии: 1.4 .replaceWith( function )
The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call. Consider this DOM structure:
div class="container">
div class="inner first">Hello div>
div class="inner second">And div>
div class="inner third">Goodbye div>
div>
The second inner could be replaced with the specified HTML:
$( "div.second" ).replaceWith( "
New heading
" );
This results in the structure:
div class="container">
div class="inner first">Hello div>
h2>New heading h2>
div class="inner third">Goodbye div>
div>
All inner elements could be targeted at once:
$( "div.inner" ).replaceWith( "
New heading
" );
This causes all of them to be replaced:
div class="container">
h2>New heading h2>
h2>New heading h2>
h2>New heading h2>
div>
An element could also be selected as the replacement:
$( "div.third" ).replaceWith( $( ".first" ) );
This results in the DOM structure:
div class="container">
div class="inner second">And div>
div class="inner first">Hello div>
div>
This example demonstrates that the selected element replaces the target by being moved from its old location, not by being cloned.
The .replaceWith() method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.
Дополнительные замечания:
- The .replaceWith() method removes all data and event handlers associated with the removed nodes.
- Prior to jQuery 1.9, .replaceWith() would attempt to add or change nodes in the current jQuery set if the first node in the set was not connected to a document, and in those cases return a new jQuery set rather than the original set. The method might or might not have returned a new result depending on the number or connectedness of its arguments! As of jQuery 1.9, .after() , .before() , and .replaceWith() always return the original unmodified set. Attempting to use these methods on a node without a parent has no effect—that is, neither the set nor the nodes it contains are changed.
- Ajax
- Глобальные Ajax события
- Вспомогательные методы
- Низкоуровневый интерфейс
- Сокращенные методы
- Базовые
- Пользовательские
- Затухание
- Скольжение
- События браузера
- Загрузка документа
- Прикрепление обработчиков
- Объект событие
- События формы
- События клавиатуры
- События мыши
- Class атрибут
- Копирование
- DOM Вставка вокруг
- DOM Вставка внутрь
- DOM Вставка вне
- DOM Удаление
- DOM Замена
- Общие аттрибуты
- Свойства стилей
- Манипуляция коллекциями
- Хранилище данных
- DOM методы элементов
- Методы установки
- Экземпляр объекта jQuery
- Глобальный объект jQuery
- Атрибут
- Базовые
- Базовые фильтры
- Фильтры потомков
- Фильтры содержимого
- Форма
- Иерархия
- jQuery расширение
- Фильтр видимости
- Фильтрация
- Обход
- Обход элементов
- Версия 1.3
- Версия 1.7
- Версия 1.8
- Версия 1.9
- Версия 1.10
- Версия 3.0
Русская документация по jQuery.
При использовании любых материалов с сайта ссылка на сайт обязательна.