Doing replace or append on a p?

2

I was trying to make an append or replace in jquery from an HTML but I'm not succeeding at it, it replaces only one <p> that contains class .frete-gratis but wanted to replace all with iframe .

Here is the code I'm currently trying to work:

var $wrapper = document.querySelector('.frete-gratis'),
// Pega a string do conteúdo atual
HTMLTemporario = $wrapper.innerHTML,
// Novo HTML que será inserido
HTMLNovo = '<iframe allowtransparency="true" src="http://aws.glamour.com.br/quero_bazar/flag-counts/index.html"height="20" width="140"></iframe>';

// Concatena as strings colocando o novoHTML antes do HTMLTemporario
HTMLTemporario = HTMLNovo + HTMLTemporario;

// Coloca a nova string(que é o HTML) no DOM
$wrapper.innerHTML = HTMLTemporario;

Is it possible to work something like this?

    
asked by anonymous 15.07.2015 / 18:30

2 answers

2

With jQuery you can use the prepend method (to add at the beginning of the element (s)) or append (to add at the end):

  // var é para variável ser local, não criando uma variável global tendo a possibilidade de dar conflito com outras bibliotecas.
  var HTMLNovo = '<iframe allowtransparency="true" src="http://aws.glamour.com.br/quero_bazar/flag-counts/index.html"height="20" width="140"></iframe>';
$('.frete-gratis').prepend(HTMLNovo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divclass="frete-gratis">DIV1: </div>
<div class="frete-gratis">DIV2: </div>
<div class="frete-gratis">DIV3: </div>
<div class="frete-gratis">DIV4: </div>
    
15.07.2015 / 18:44
4

Note: You are not using jQuery but rather working with pure and hard JavaScript.

You are using the document.querySelector() method that returns you only the first element found:

  

Returns the first element within the document (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors.

What translated:

  

Returns the first element within the document (using the depth-first pre-order document nodes crossing) that matches the specified group of selectors.

What you are looking for is the document.querySelectorAll() method that returns you a list of elements:

  

Returns the list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.

What translated:

  

Returns a list of elements within the document (using the depth-first pre-order document node traversal) that correspond to the specified group of selectors. The returned object is a NodeList.

Your code would look like this:

var wrappers = document.querySelectorAll('.frete-gratis');

[].forEach.call(wrappers, function(wrap) {

  // fazer o que pretendes, por exemplo mudar a cor
  wrap.style.color = "red";
});
    
15.07.2015 / 18:50