it_is_a_literature it_is_a_literature - 1 month ago 11
Javascript Question

How to read the external html file as a DOM tree?

The data.html file is simple such as below.

<table id="test">
<tr>
<td>f1</td>
<td>f2</td>
</tr>
<tr>
<td>y</td>
<td>70</td>
</tr>
</table>


I can read it with FileReader.




function readAsText(){
var file = document.getElementById("file").files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload=function(){
_table=this.result;
alert(_table);
}
}

<p>
<label>to select a file</label>
<input type="file" id="file" />
<input type="button" value="read as text" onclick="readAsText()" />
</p>





enter image description here
enter image description here

The data.html can be read as a text file not DOM tree,how to read it as a dom tree?

How to get the rows number of data.html file?

_table.rows.length
can not get the rows number because the _table is not a dom tree,can i change it into a dom tree to operate?

_table=this.result;
alert(_table.rows.length);

Answer

The DOMParser API does just that :

var markup = '<table id="test">'+
'<tr>'+
'<td>f1</td>'+
'<td>f2</td>'+
'</tr>'+
'<tr>'+
'<td>y</td>'+
'<td>70</td>'+
'</tr>'+
'</table>';

var parsedDoc = new DOMParser().parseFromString(markup, 'text/html');
console.log('number of rows:', parsedDoc.getElementById('test').rows.length)

console.log('textContent of the fourth td:',parsedDoc.querySelectorAll('td')[3].textContent);