.after () jquery in JS Pure?

5

In jquery:

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

How would you look in pure JS?

    
asked by anonymous 06.11.2015 / 07:05

2 answers

4

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

A posição is defined relative to the element by the following types:

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

And the placement would look like:

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

conteúdo is a 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>
    
06.11.2015 / 19:45
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 the child of the current node.

     

(...)

     

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

In this way, you must insert the new node in the parent element before the next sibling element.

The short form is:

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

The code below adds a new node as it is done in the question, it 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>
    
06.11.2015 / 11:24