Insert Tags from Console

Asked

Viewed 110 times

0

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

I’ve tried using the document.createElement('tag'), after that add the tag attributes by appendchild. but did not succeed.

I also tried to create one and add the tag and attributes through text, but it didn’t work.

document.createElement('div').innerHTML="<iframe id="" frameborder="0" style="" scrolling="auto" src="" allowfullscreen></iframe> "
  • By the console? It wouldn’t be by javascript?

3 answers

1

You can use the 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>

1

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

You can also use insertAdjacentHTML to 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 in place of position

beforebegin: Before the Element

afterbegin: Inside the element and before your first child

beforeend: Inside the element and after your last child

afterend: After the element

// 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>

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

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 creates an element with Document.createelement() , then assigns values to the element properties (representing the element attributes) and at the end adds the element (iframe) to the element body with the method appendchild .

Browser other questions tagged

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