Insert Tags by Console

0

I need to insert Tags into a site through the console. To be more specific, I want to add a TAG <iframe></iframe> .

I have already tried to use document.createElement('tag') , after that add the attributes of the tag by appendChild. but I was not successful.

I also tried to create one and add the tag and attributes through text, but it did not work.

document.createElement('div').innerHTML="<iframe id="" frameborder="0" style="" scrolling="auto" src="" allowfullscreen></iframe> "
    
asked by anonymous 29.01.2018 / 15:47

3 answers

0

The following code should serve:

var iframe = document.createElement('iframe');
iframe.id = '';
iframe.frameBorder = '0';
iframe.style = '';
iframe.scrolling = 'auto';
iframe.src = '';
iframe.allowFullscreen = 'true';
document.body.appendChild(iframe);

First create an element with Document.createElement () , then assigns values to the element properties (which represent the attributes of the element) and at the end adds the element ( iframe ) to the body element. with the appendChild .

    
29.01.2018 / 16:21
1

You can use createElement() , followed by appendChild() .

var target = document.getElementById('target');

var elemento = document.createElement('iframe');
elemento.frameBorder = 0;
elemento.style = "";
elemento.scrolling = "";
elemento.src = "";
elemento.id = "novo-iframe";

target.appendChild(elemento);

console.log(document.getElementById('novo-iframe'));
<html>

<body>
  <div id="target"></div>
</body>

</html>
    
29.01.2018 / 16:09
1

Your last code did not work because you are not inserting the element created in your page, and you are not escaping the "(quotation marks) of the attributes.

You can also use insertAdjacentHTML for insert an HTML code into your page.

element.insertAdjacentHTML("posição", "código-html);

To control where you want the element, simply add one of the values below instead of position

  

Beforebegin: Before Element

  

afterbegin: Inside the element and before your first child

  

beforeend: Inside the element and after your last child

  

afterend: After the

// Captura o elemento onde queremos adicionar
var target = document.querySelector('#target');

// Código do iframe
var elemento = '<iframe frameborder="0" id="novo-iframe" src="/"></iframe>';

// Adicionamos o iframe dentro do elemento capturado
target.insertAdjacentHTML('beforeend', elemento);

// Exibidos o código do iframe criado no console
console.log(document.getElementById('novo-iframe'));
iframe {
  height: 14em;
  width: 100%
}
<div id="target"></div>

With jQuery

$('#target').append('<iframe frameborder="0" id="novo-iframe" src="/"></iframe>');
iframe {
  height: 14em;
  width: 100%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="target"></div>
    
29.01.2018 / 16:18