.after() jquery on JS Pure?

Asked

Viewed 273 times

5

In jquery:

$( "#main article:nth-child(3)" ).after( "<div style='clear:both;/>" );

How would I look in pure JS?

2 answers

8

The jQuery function .after() inserts a sibling element later, in native javascript this is done with insertBefore(), according to the documentation:

(insertBefore) Adds the specified node, before a reference element, as child of the current node.

(...)

There is no method insertAfter. But it can be emulated by combining the method insertBefore with nextSibling.

This way you must insert the new node into the parent element before the next sibling element.

The short form stays:

elemento.parent.insertBefore(novoElemento, elemento.nextSibling);

The code below adds a new node as it is asked in the question, is easy to understand and the comments complement.

var elementos = document.querySelectorAll('span:nth-child(3)');
var elemento, pai, div;
for (var i = 0; i < elementos.length; i++) {
  elemento = elementos[i];
  pai = elemento.parentNode;
  div = document.createElement('div');
  div.style.clear = 'both';
  // insere no elemento pai, antes do próximo irmão
  pai.insertBefore(div, elemento.nextSibling)
  // se o segundo parâmetro é nulo será inserido como último filho
}

// se for apenas um elemento utilize a linha abaixo
// e apague o loop for
var elemento = document.querySelector('li:nth-child(3)');
<span>item</span>
<span>item</span>
<span>item</span>
<span>item</span>

  • Good point, ++

4


Use insertAdjacentHTML(posição, conteúdo) (support):

To posição is defined for the element by the following types:

  • "afterbegin": Inside the element, before your first child (childNode).
  • "afterend": After the element itself.
  • "beforebegin": Before the element itself.
  • "beforeend": Inside the element, after your last child (childNode).

And the positioning would be:

<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo 
<!-- beforeend -->
</p>
<!-- afterend -->`

The conteúdo is string to be parsed as HTML or XML and inserted into the tree.


Example:

var elemento = document.querySelector('p');
elemento.insertAdjacentHTML('afterend', '<p>Overflow</p>');
p { display: inline }
<p>Stack</p>

  • good response, +1. From the documentation I saw the function insertAdjacentHTML accepts HTML as text but not an element created for example with createElement. Meanwhile Chrome and IE have a method insertAdjacentElement, even if no such method exists in recommendation W3C

Browser other questions tagged

You are not signed in. Login or sign up in order to post.