Удаление html кода jquery

Изменение HTML через jQuery часть 1 (html, wrap, remove, empty)

Библиотека jQuery обладает целым набором отличных методов для изменения HTML. В этой статье рассмотрим часть из наиболее востребованных.

Чтение и изменение содержания тегов (html)

Метод html позволяет изменять или считывать содержание тегов. Если предать ему параметр, то произойдёт замена содержание тега не переданное значение. Если параметр не передавать, то произойдёт считывание. Продемонстрируем обе эти функции:

Тише, мыши, кот на крыше

В этом примере в первом случае использования метода html не передаётся никакого параметра в скобках. Поэтому метод возвращает HTML содержание элемента. Во втором случае ему передаётся строка с HTML тегом. Эта строка заменяет содержание элемента. В итоге на странице получится такой HTML код:

Тише, мыши, сыр на крыше

Обратите внимание, что из-за особенности работы селекторов в jQuery, действие будет произведено над всеми элементами, которые удовлетворяют условию, а не только над первым. То есть если выполнить код $(‘div’).html(‘ ‘), то HTML код во всех контейнерах на сайте будет заменён на пробел » «. Функция не остановится после первой замены.

То же самое можно сказать и о всех других методах, приведённых в этой статье.

Оборачивание элементов в HTML теги (wrap, wrapAll)

Метод wrap позволяет оборачивать элементы в выбранный тег. В параметре этого метода можно написать как название тега, в который надо обернуть (к примеру wrap(‘div’)), так и код тега полностью (к примеру wrap(‘ ‘)). Во втором случае можно задать ещё и атрибуты для тега-обёртки, к примеру класс или стиль: wrap(‘ ‘). Продемонстрируем оба способа:

Тише, мыши, кот на крыше А котята ещё выше  
Тише, мыши, кот на крыше
А котята ещё выше

Если понадобится обернуть не каждый элемент отдельно, а оба элемента в один тег, то можно воспользоваться методом wrapAll. Но для этого надо использовать тот селектор, который будет подходить к нескольким элементам. К примеру, сгруппируем по одному классу несколько элементов:

Тише, мыши, кот на крыше А котята ещё выше  
 
Тише, мыши, кот на крыше А котята ещё выше

При выполнении метода wrapAll необходимо учитывать что если между выбираемыми элементами окажутся сторонние, которые не подходят под условие, то они будут принудительно передвинуты и окажутся после обёрнутого набора.

Читайте также:  Import java package in android

Удаление элементов или содержимого (remove, empty)

Иногда появляется необходимость не просто скрыть элемент, а совсем удалить его со страницы. Для этого можно использовать метод remove. Попробуем с помощью этого метода удалить из предыдущего примера первый тег:

Тише, мыши, кот на крыше А котята ещё выше  

Существует метод empty, который удаляет содержимое элемента. То есть этот метод работает точно так же, как если если использовать метод html(»), у которого в скобках стоит строка с нулевой длиной (то есть кавычки открываются и сразу закрываются:

Тише, мыши, кот на крыше

Источник

.remove()

Description: Remove the set of matched elements from the DOM.

version added: 1.0 .remove( [selector ] )

Similar to .empty() , the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

Consider the following HTML:

div class="container">
div class="hello">Hello div>
div class="goodbye">Goodbye div>
div>

We can target any element for removal:

This will result in a DOM structure with the element deleted:

div class="container">
div class="goodbye">Goodbye div>
div>

If we had any number of nested elements inside , they would be removed, too. Other jQuery constructs such as data or event handlers are erased as well.

We can also include a selector as an optional parameter. For example, we could rewrite the previous DOM removal code as follows:

This would result in the same DOM structure:

div class="container">
div class="goodbye">Goodbye div>
div>

Examples:

Removes all paragraphs from the DOM

html>
html lang="en">
head>
meta charset="utf-8">
title>remove demo title>
style>
p
background: yellow;
margin: 6px 0;
>
style>
script src="https://code.jquery.com/jquery-3.7.0.js"> script>
head>
body>
p>Hello p>
how are
p>you? p>
button>Call remove() on paragraphs button>
script>
$( "button" ).on( "click", function( )
$( "p" ).remove();
> );
script>
body>
html>

Demo:

Removes all paragraphs that contain "Hello" from the DOM. Analogous to doing $("p").filter(":contains('Hello')").remove() .

html>
html lang="en">
head>
meta charset="utf-8">
title>remove demo title>
style>
p
background: yellow;
margin: 6px 0;
>
style>
script src="https://code.jquery.com/jquery-3.7.0.js"> script>
head>
body>
p class="hello">Hello p>
how are
p>you? p>
button>Call remove( ":contains('Hello')" ) on paragraphs button>
script>
$( "button" ).on( "click", function( )
$( "p" ).remove( ":contains('Hello')" );
>);
script>
body>
html>

Demo:

  • Ajax
    • Global Ajax Event Handlers
    • Helper Functions
    • Low-Level Interface
    • Shorthand Methods
    • Deprecated 1.3
    • Deprecated 1.7
    • Deprecated 1.8
    • Deprecated 1.9
    • Deprecated 1.10
    • Deprecated 3.0
    • Deprecated 3.2
    • Deprecated 3.3
    • Deprecated 3.4
    • Deprecated 3.5
    • Basics
    • Custom
    • Fading
    • Sliding
    • Browser Events
    • Document Loading
    • Event Handler Attachment
    • Event Object
    • Form Events
    • Keyboard Events
    • Mouse Events
    • Class Attribute
    • Copying
    • DOM Insertion, Around
    • DOM Insertion, Inside
    • DOM Insertion, Outside
    • DOM Removal
    • DOM Replacement
    • General Attributes
    • Style Properties
    • Collection Manipulation
    • Data Storage
    • DOM Element Methods
    • Setup Methods
    • Properties of jQuery Object Instances
    • Properties of the Global jQuery Object
    • Attribute
    • Basic
    • Basic Filter
    • Child Filter
    • Content Filter
    • Form
    • Hierarchy
    • jQuery Extensions
    • Visibility Filter
    • Filtering
    • Miscellaneous Traversing
    • Tree Traversal
    • Version 1.0
    • Version 1.0.4
    • Version 1.1
    • Version 1.1.2
    • Version 1.1.3
    • Version 1.1.4
    • Version 1.2
    • Version 1.2.3
    • Version 1.2.6
    • Version 1.3
    • Version 1.4
    • Version 1.4.1
    • Version 1.4.2
    • Version 1.4.3
    • Version 1.4.4
    • Version 1.5
    • Version 1.5.1
    • Version 1.6
    • Version 1.7
    • Version 1.8
    • Version 1.9
    • Version 1.11 & 2.1
    • Version 1.12 & 2.2
    • Version 3.0
    • Version 3.1
    • Version 3.2
    • Version 3.3
    • Version 3.4
    • Version 3.5
    • Version 3.6
    • Version 3.7

    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

    Источник

    Category: DOM Removal

    These methods allow us to delete elements from the DOM.

    .detach()

    Remove the set of matched elements from the DOM.

    .empty()

    Remove all child nodes of the set of matched elements from the DOM.

    .remove()

    Remove the set of matched elements from the DOM.

    .unwrap()

    Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

    • Ajax
      • Global Ajax Event Handlers
      • Helper Functions
      • Low-Level Interface
      • Shorthand Methods
      • Deprecated 1.3
      • Deprecated 1.7
      • Deprecated 1.8
      • Deprecated 1.9
      • Deprecated 1.10
      • Deprecated 3.0
      • Deprecated 3.2
      • Deprecated 3.3
      • Deprecated 3.4
      • Deprecated 3.5
      • Basics
      • Custom
      • Fading
      • Sliding
      • Browser Events
      • Document Loading
      • Event Handler Attachment
      • Event Object
      • Form Events
      • Keyboard Events
      • Mouse Events
      • Class Attribute
      • Copying
      • DOM Insertion, Around
      • DOM Insertion, Inside
      • DOM Insertion, Outside
      • DOM Removal
      • DOM Replacement
      • General Attributes
      • Style Properties
      • Collection Manipulation
      • Data Storage
      • DOM Element Methods
      • Setup Methods
      • Properties of jQuery Object Instances
      • Properties of the Global jQuery Object
      • Attribute
      • Basic
      • Basic Filter
      • Child Filter
      • Content Filter
      • Form
      • Hierarchy
      • jQuery Extensions
      • Visibility Filter
      • Filtering
      • Miscellaneous Traversing
      • Tree Traversal
      • Version 1.0
      • Version 1.0.4
      • Version 1.1
      • Version 1.1.2
      • Version 1.1.3
      • Version 1.1.4
      • Version 1.2
      • Version 1.2.3
      • Version 1.2.6
      • Version 1.3
      • Version 1.4
      • Version 1.4.1
      • Version 1.4.2
      • Version 1.4.3
      • Version 1.4.4
      • Version 1.5
      • Version 1.5.1
      • Version 1.6
      • Version 1.7
      • Version 1.8
      • Version 1.9
      • Version 1.11 & 2.1
      • Version 1.12 & 2.2
      • Version 3.0
      • Version 3.1
      • Version 3.2
      • Version 3.3
      • Version 3.4
      • Version 3.5
      • Version 3.6
      • Version 3.7

      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

      Источник

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