Reputation: 31
If i have the http.responseText stored in a javascript variable e.g named sourcecode which contains the whole source code of the page from which i want to extract everything between the table tags into a javascript variable how do i do that? The html code looks like this:
<table border="0" width="100%" cellspacing="0" cellpadding="0" class="statusbox_ok" style="margin-top: 5px; margin-bottom: 5px">
<tbody><tr>
<td align="left" valign="top"><img src="http://www.10eastern.com/images/FoundPhotos/archives/archive118/dasdsa.jpg" style="margin: 2px; margin-right: 10px"></td>
<td align="left" valign="middle" width="100%">
Your new username is Tom. </td>
</tr>
</tbody></table>
I want to at least be able to extract:
<td align="left" valign="middle" width="100%">
Your new username is Tom. </td>
It doesn't matter if it includes everything between the tbody or whole table tags as well, but that part is crucial to be extracted into a javascript variable.
How do i do this without jquery
?
Thanks.
Upvotes: 3
Views: 6846
Reputation: 20486
Update:
Using this article, I read about DOMParser()
which lets you parse a string into a DOM element with Javascript. Using .parseFromString()
, I was able to parse an HTML string into a DOM element.
var html = '<html><table /></html>'; // Your source code
html = new DOMParser().parseFromString(html, "text/html");
Just make sure you update document.getElementsByTagName('table')
with html.getElementsByTagName('table')
, since we are now looking for tables in our parsed string not the document.
Updated JSFiddle.
I avoided using RegEx, because HTML isn't a regular language and you shouldn't use regular expressions to match it. Also, there are enough pure Javascript functions to accomplish your task.
var tables = document.getElementsByTagName('table');
for(var tableIt = 0; tableIt < tables.length; tableIt++) {
var table = tables[tableIt];
if(table.className === 'statusbox_ok') {
var columns = table.getElementsByTagName('td');
for(columnIt = 0; columnIt < columns.length; columnIt++) {
var column = columns[columnIt];
console.log(column.innerHTML);
}
}
}
I looped through all of your table elements with .getElementsByTagName()
. Then check the .className
to make sure it is your statusbox_ok
table. We once again use .getElementsByTagName()
to loop through all of the columns. You can use some logic here to determine which column you want (similar to what we did with the table's class), but then I logged the HTML contents of each column with .innerHTML
.
Check out this JSFiddle for a working example.
Upvotes: 5