Enter arbitrary HTML string in a document (javascript) - updated

Update: I just narrowed my problem:

Why this does not work:

var tmp = document.createElement('tbody');
tmp.innerHTML="<tr><td>hello</td></tr>";

tmp gets the string hello. tr and td html is lost (on FireFox). Why is this? and how can i make such an html injection?

The original question:

I need to enter arbitrary HTML after an arbitrary element into arbitrary HTML documents. I came across this method (we insert the html line into the dynamically generated div, get our first element and paste it in the right place):

var tmp = document.createElement('div'); 
tmp.innerHTML = _injected_html;
var new_w = tmp.firstChild;
var parent = insertion_point.parentNode;
parent.insertBefore(new_w, insertion_point.nextSibling);

The problem is that this does not work when trying to enter table elements. if the html entered is, for example,

"<tr> <td> table data </td> </tr>"

_tmp.innerHTML = _injected_html; will not accept it (adding tr under the div element).

Any idea how to make this work for any tag?

+3
4

IE ? , .

edit: , - , <div><tr><td>... . document.createElement('div') document.createElement('tr') <tr> _injected_html?

- ( Firefox):

<script>
var i = 3;

function f() {
    var table = document.getElementById('someTable');
    var children = table.children[0].children;
    var after = children[Math.round(Math.random() * (children.length - 1))];
    var html = "<td>" + i++ + "</td>";

    g(html, after);
}

function g(_injected_html, insertion_point) {
    var tmp = document.createElement('tr'); 
    tmp.innerHTML = _injected_html;
    var new_w = tmp.firstChild;
    var parent = insertion_point.parentNode;
    parent.insertBefore(new_w, insertion_point.nextSibling);
}
</script>

<table id="someTable" onclick="f();">
    <tr><td>1</td></tr>
    <tr><td>2</td></tr>
</table>

f() , ( <tbody>, ( <tr> s).

+2
<div><td><lol/>

.. HTML! //, , .. - HTML , ?

0

tr tbody. html

<table><tr><td>abc</td></tr></table>

IE, FF, Chrome, Safari ( ) :

<table><tbody><tr><td>abc</td></tr></tbody></table>

, - :

var tmp = document.createElement('tr'); 
tmp.innerHTML = "<td>def</td>";
var new_w = tmp.firstChild;
var parent = insertion_point.parentNode;
parent.insertBefore(new_w, insertion_point.nextSibling);

, insertion_point - -.

But frankly, with Jquery there are more elegant ways to get around this as notes on Christina's note.

0
source

The following javascript will allow you to inject HTML / etc into a local page:

var example = "<p>test</p>"
document.body.appendChild(example); 

However you should customize the code depending on what you insert.

-1
source

Source: https://habr.com/ru/post/1713895/


All Articles