greenflame wrote:
So I am trying to implement the following in DOM:
document.write(str);
I was wondering if the following would do it:
document.createT*extNode(str);
So I tryed it and it showed nothing.
I was wondering what will.
Having created your text node, you must add it to the document. Usually
you locate a suitable element using getElementById, or have a reference
passed to your write function from a calling function, then add your
text node to that.
So for your example:
<div id="textHolder"></div>
<input type="button" value="Add some text" onclick="
addText( 'Here is some text', 'textHolder' );
">
<script type="text/javascript">
function addText( str, elID ){
var aDiv = document.getElementById( elID );
var oTxt = document.createTextNode( str );
aDiv.appendChild( str );
}
</script>
Guessing at what you might use this for, here is a showMatrix() function
that will put a matrix (array of arrays) inside a table. You pass it a
reference to the matrix and the ID of the element to put the table
inside of (it should be a div or table cell or similar block level
element that can have an other block level element inside it).
The routine will handle a matrices with one or more rows of one or more
elements, but they must be matrices (or '2D arrays'). You can add
styles for classes 'mDiv' and 'mCell' to control the appearance of the
table.
// Show a matrix in a table
function showMatrix( X, elID ){
// Locate the element to add the matrix table to
var el = document.getElementById( elID );
// Check that X really is a matrix
if ( !X
|| 'object' != typeof X
|| Array != X.constructor ) {
var msg = 'showMatrix: didn\'t get a matrix';
el.appendChild( document.createTextNode( msg ) );
return;
}
// Setup variable
var i=0, j=X.length; // row counter
var m=0, n=X[i].length; // element counter
var cr; // current row
// Start making table & components
var oT = document.createElement('table');
var oTb = document.createElement('tbody');
var oTr, oTd;
// Create a new row
while ( i < j ) {
cr = X[i++];
oTr = document.createElement('tr');
m = 0;
// Append a cell for each element with the value inside
while ( m < n ) {
oTd = document.createElement('td');
oTd.className = 'mCell';
oTd.appendChild(document.createTextNode( cr[m++] ));
oTr.appendChild( oTd );
}
// Append the row to the table body
oTb.appendChild( oTr );
}
// Add a few niceties
oT.className = 'mTable';
// Add the body to the table and the table to the document
oT.appendChild( oTb );
el.appendChild( oT );
}
--
Rob