Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting String as Elements to the DOM for javascript?

Tags:

javascript

dom

I have a test chunk of HTML, as an example::

The HTML is a string, and not a DOM element, but I'm trying to see if there i a way, or an approach that can be used to insert the string as the DOM, so it can be appended to the DOM.

var test='<tr class="rowHeaders">';
test=test+'<td id="sTD" name="sTD" width="4%">test.php</td>'
test=test+'<td width="2%"><input type="radio" name="tb" ></td>';
test=test+'<td id="tTD" name="tTD" width="2%">php</td>';
test=test+'<td width="2%"><input type="button" name="vv" ></td>';
test=test+'</tr>';


var scriptTBL=document.getElementById("scriptsT");

scriptTBL.children[0].appendChild(test);

Trying to do something like this...

But "test" isn't a valid node, or element, so how can i add it to the element??

I thought about using the innerHtml, but there might already be an existing child for the table/tbody for the DOM.

I've been exploring fragments, but this isn't clicking!

The test html has the tbl:

<table id="scriptsT" name="scriptsT" >
  <tr>
    .
    .

Pointers or thoughts would be greatly appreciated.

Thank you.

like image 279
bobby 1 Avatar asked Jul 10 '26 17:07

bobby 1


2 Answers

You could append to the innerHTML:

scriptTBL.tBodies[0].innerHTML += test;

foo += bar is shorthand for foo = foo + bar. You can also simplify your HTML creation code this way. Use test += 'html here';.

appendChild only accepts a DOM element.

like image 62
Felix Kling Avatar answered Jul 14 '26 00:07

Felix Kling


Make a div (or span or whatever) and load your fragment with innerHTML.

var someDiv = document.createElement("div");
someDiv.innerHTML = "<tr ....  ";
someParentElement.appendChild(someDiv);
like image 28
Jim Blackler Avatar answered Jul 14 '26 02:07

Jim Blackler