Добавить html после элемента

Содержание
  1. Insert an element after another DOM element with JavaScript
  2. You might also like.
  3. .after()
  4. .after( content [, content ] ) Возвращает: jQuery
  5. Добавлен в версии: 1.0 .after( content [, content ] )
  6. Добавлен в версии: 1.4 .after( function )
  7. Добавлен в версии: 1.10 .after( function-html )
  8. Passing a Function
  9. Additional Arguments
  10. Дополнительные замечания:
  11. Манипуляции с элементами jQuery
  12. Проверка
  13. Проверка наличия элемента:
  14. Пустой или нет:
  15. Проверка элементов до и после
  16. Перед элементом:
  17. После элемента:
  18. Добавление
  19. Вставить перед элементом:
  20. Вставить после элемента:
  21. Пример работы before и after:
  22. Добавить до n-го элемента:
  23. Добавить после n-го элемента:
  24. Добавить в начало элемента:
  25. Добавить в конец элемента:
  26. Пример работы prepend и append:
  27. Оборачивание
  28. Обернуть элемент снаружи
  29. Пример работы wrap:
  30. Обернуть несколько элементов одним
  31. Пример работы wrapAll:
  32. Обернуть содержимое элемента
  33. Пример работы wrapInner:
  34. Замена
  35. Клонирование
  36. Пример работы clone:
  37. Удаление
  38. Удалить элемент с содержимым:
  39. Изменение HTML через jQuery часть 2 (prepend, append, before, after, insert)
  40. Добавление в начало и конец элемента (prepend, append)
  41. Добавление до и после элемента (before, after)

Insert an element after another DOM element with JavaScript

In earlier articles, we looked at how to create and element and insert it before another HTML element in the DOM using vanilla JavaScript.

In this article, you’ll learn different ways to insert an element after another one in the DOM with JavaScript.

The insertBefore() method, which we learned earlier to add an element before, can also be used to insert an HTML element after an HTML node. For this purpose, we need to use the element’s nextSibling property that returns a reference to the next node at the same tree level.

// create a new element const elem = document.createElement('p') // add text elem.innerText = 'I am a software engineer.' // grab target element reference const target = document.querySelector('#intro') // insert the element after target element target.parentNode.insertBefore(elem, target.nextSibling) 

The insertBefore() method works in all modern and old browsers, including Internet Explorer 6 and higher.

Читайте также:  Cms for php database

If you want to insert an HTML string after a certain element in the DOM, use the insertAdjacentHTML() instead, like below:

// insert HTML string after target element target.insertAdjacentHTML('afterend', '

I am a software engineer.

'
)

The insertAdjacentHTML() method automatically parses the given string as HTML and inserts the resulting elements into the DOM tree at the given position. Read this guide to learn more about it.

ES6 introduced a new method called after() to insert an element right after an existing node in the DOM. Just call this method on the element you want to insert an element after, and pass the new element as an argument:

// insert the element after the target element target.after(elem) 

The after() method only works in modern browsers, specifically Chrome, Safari, Firefox, and Opera. At the moment, Internet Explorer doesn’t support this method. However, you can use a polyfill to bring the support up to IE 9 and higher. Read Next: How to insert an element to the DOM in JavaScript ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

.after()

.after( content [, content ] ) Возвращает: jQuery

Описание: Функция вставляет заданное содержимое сразу после определенных элементов страницы.

Добавлен в версии: 1.0 .after( content [, content ] )

HTML string, DOM element, text node, array of elements and text nodes, or jQuery object to insert after 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 after each element in the set of matched elements.

Добавлен в версии: 1.4 .after( function )

A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.

Добавлен в версии: 1.10 .after( function-html )

A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert after 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 .after() and .insertAfter() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With .after() , the content to be inserted comes from the method’s argument: $(target).after(contentToBeInserted) . With .insertAfter() , on the other hand, the content precedes the method and is inserted after the target, which in turn is passed as the .insertAfter() method’s argument: $(contentToBeInserted).insertAfter(target) .

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

Content can be created and then inserted after several elements at once:

Each inner element gets this new content:

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

An element in the DOM can also be selected and inserted after another element:

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved rather than cloned:

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

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.

Passing a Function

As of jQuery 1.4, .after() supports passing a function that returns the elements to insert.

$( "p" ).after(function()
return "
" + this.className + "
"
;
>);

This example inserts a after each paragraph, with each new containing the class name(s) of its preceding paragraph.

Additional Arguments

Similar to other content-adding methods such as .prepend() and .before() , .after() 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 after the first paragraph:

var $newdiv1 = $( " " ),
newdiv2 = document.createElement( "div" ),
existingdiv1 = document.getElementById( "foo" );
$( "p" ).first().after( $newdiv1, [ newdiv2, existingdiv1 ] );

Since .after() 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: $( "p" ).first().after( $newdiv1, newdiv2, existingdiv1 ) . The type and number of arguments will largely depend on the elements that are collected in the code.

Дополнительные замечания:

  • Prior to jQuery 1.9, .after() 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.
  • 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

Сборник методов jQuery для управления элементами DOM.

Проверка

Проверить элементы на наличие, заполненность можно с помощью следующих способов:

Проверка наличия элемента:

Пустой или нет:

if ($('.element').is(':empty')) < alert('.element пуст'); >if ('.element:not(:empty)')

Проверка элементов до и после

Комбинацией методов prev() , next() и is() можно узнать о предыдущем и последующим элемент в общем родителе.

Перед элементом:

if ($('.element').prev().is('div')) < alert('Перед .element есть div'); >if ($('.element').prev().is(':empty'))

После элемента:

if ($('.element').next().is('div')) < alert('После .element есть div'); >if ($('.element').next().is(':empty'))

Добавление

Вставить перед элементом:

$('ul').before('

Новый параграф

'); /* или */ $('

Новый параграф

').insertBefore('ul');

Вставить после элемента:

$('ul').after('

Новый параграф

'); /* или */ $('

Новый параграф

').insertAfter('ul');

Пример работы before и after:

Далее, селектором :eq(n) можно добавить контент у порядкового элемента.

Добавить до n-го элемента:

$('ul:eq(1)').before('

Новый параграф

');

Добавить после n-го элемента:

Добавить в начало элемента:

Добавить в конец элемента:

Пример работы prepend и append:

Оборачивание

Обернуть элемент снаружи

wrap() – оборачивает каждый выбранный элемент в указанную обертку.

Пример работы wrap:

Ещё один пример оборачивает все изображения ссылками:

Обернуть несколько элементов одним

$('p').wrapAll(''); /* Так-же можно указать список элементов */ $('.class1, .class2, .class3').wrapAll('');

Пример работы wrapAll:

Обернуть содержимое элемента

$('.element').wrapInner(' '); /* или */ $('.element').wrapInner('');

Пример работы wrapInner:

Замена

Методы replaceWith() или replaceAll() заменяют элемент другим элементом, включая его содержимое.

$('div').replaceWith('

123

'); /* или */ $('

123

').replaceAll('div');

Если нужно заменить тег, но оставить его содержимое:

$('.element').replaceWith('

' + $('.element').html() + '

'); /* или */ $('

' + $('.element').html() + '

').replaceAll('.element');

Если нужно сохранить все атрибуты старого тега и содержимое:

$('#element').replaceWith(function()< $new = $('

', ); $.each(this.attributes, function(i, attribute)< $new.attr(attribute.name, attribute.value); >); return $new; >);

Клонирование

.clone(withDataAndEvents, deepWithDataAndEvents) – создает копию элемента, если в параметре withDataAndEvents указать true, то так-же скопируются все данные и обработчики элемента. Параметр deepWithDataAndEvents отвечает за копирование обработчиков у дочерних элементов, по умолчанию равен withDataAndEvents .

 var new_element = $('.element').clone(true); $('body').append(new_element);

Пример работы clone:

Удаление

Метод remove() удаляет элемент полностью, включая повешенные на него события и освобождает память.

Удалить элемент с содержимым:

Метод detach() как бы скрывает элемент, поэтому если повторно добавить этот элемент в DOM, он сохранит все события и свойства.

Источник

Изменение HTML через jQuery часть 2 (prepend, append, before, after, insert)

Для добавления HTML элементов на страницу в библиотеке jQuery есть целый набор методов. Они позволяют вставлять код до и после определённых узлов, внутри и снаружи. Разберём как использовать их.

Добавление в начало и конец элемента (prepend, append)

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

Тише, мыши, кот на крыше
/начало/Тише, мыши, кот на крыше/конец/

- в примере в начало и конец строки были добавлены строки '/начало/' и '/конец/'. Но можно добавлять и строки с HTML кодом. К примеру, можно вместо '/начало/' поставить '/начало/', и вместо '/конец/' поставить '/конец/'

Существуют два метода, которые являются родственниками (практически синонимами) приведённых в этом параграфе. Это методы appendTo и prependTo. Разница незначительная в том, что если в "prepend" и "append" надо передавать HTML код, который будет вставлен, то в "appendTo" и "prependTo" надо передавать селектор элементов. То есть если переписать предыдущий пример через appendTo и prependTo, то значения в круглых скобках поменяются местами:

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

Правда в отличии от "prepend" и "append" в этом примере нельзя просто поставить '/начало/' и '/конец/'. Нужно обрамить их тегами. Но результат будет полностью идентичен результату предыдущего примера:

/начало/Тише, мыши, кот на крыше/конец/

Добавление до и после элемента (before, after)

Чтобы добавить HTML код до или после элемента необходимо использовать методы before или after. Продемонстрируем это:

Тише, мыши, кот на крыше
/начало/
Тише, мыши, кот на крыше
/конец/

Как и в случае с "prepend" и "append", у "before" и "after" существуют синонимы. Это методы insertAfter и insertBefore. Разница между ними аналогичная: если в "before" и "after" надо передавать HTML код, который будет вставлен, то в "insertAfter" и "insertBefore" надо передавать селектор элементов. Если переписать предыдущий пример через insertAfter и insertBefore, то значения в круглых скобках поменяются местами:

Тише, мыши, кот на крыше
/начало/
Тише, мыши, кот на крыше
/конец/

Источник

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