简体   繁体   中英

how do i write to an html from a javascript function?

i have a problem with my javascript and html

i was trying to write a html element using a function from my javascript here's my code

function write();
{
 for(var i=0;i<arr.length;i++)
 {
  document.write("<td>"+arr[i]+"</td><br>")
 }
}

and code at my index.html, i want put that write inside my table row

<tr>
<script>write();</script>
</tr>

i have attached my javscript to my html document, but nothing happened can u guys help me to put make that function work?? thanks guys!!

As per your question description, for writing html or dom elements say, you need to first create element(until you already have in which case you can use document.getElementById() ) and then add text.

For creating:

# Create new dom element
var td = document.createElement("td");

Adding text:

td.appendChild(document.createTextNode('hiii'))

In your case:

function write(){
  var element;
  for(var i=0;i<arr.length;i++) {
    element = document.createElement("td");
    element.appendChild(document.createTextNode(arr[i]));
  }
}

Give your row an id like this:

<tr id="myRow">

</tr>

Also i would recommend you to implement the function call in your javascript file. Try something like this:

window.onload = function(){
    write();
};

function write(){
    for(var i = 0; i < arr.length; i++){
        document.getElementById("myRow").innerHTML += "<td>" + arr[i] + "</td><br>";
    }
}

you can check html below:

<table>
   <tr id="myid" >

   </tr>
</table>

and javascript would be like this

var row = document.getElementById("myid");
var x = row.insertCell(0);
x.innerHTML="New cell";

HTML:

<table>
    <tr id='row'></tr>    
</table>

JS:

function write(arr) {
    var row = '';

    for (var i = 0; i < arr.length; i++) {
        row += '<td>'+arr[i]+'</td>'
    }

    document.getElementById('row').innerHTML = row;
}

write(['a', 'b', 'c', 'd']);

working demo: http://jsfiddle.net/uhaEL/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM