it_is_a_literature it_is_a_literature - 3 years ago 93
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">

I can read it with FileReader.

function readAsText(){
var file = document.getElementById("file").files[0];
var reader = new FileReader();

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

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?

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


Answer Source

The DOMParser API does just that :

var markup = '<table id="test">'+

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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download