Javascript reverse engineering: Convert html table to string/text - javascript

Currently I have a table variable which I want to get its table content in this way: <table><tr></tr></table> instead of getting a Javascript object. Is there a solution to finding a method that could do that?

try innerHTML.

This assumes your table is the only table on the page. If this is not the case, give it a unique ID (such as tableID) and reference using getElementsById("tableID").
var tables = document.getElementsByTagName("table");
var firstTable = tables[0];
var tableAttr = firstTable.attributes;
// get the tag name 'table', and set it lower case since JS will make it all caps
var tableString = "<" + firstTable.nodeName.toLowerCase() + ">";
// get the tag attributes
for(var i = 0; i < tableAttr.length; i++) {
tableString += " " + tableAttr[i].name + "='" + tableAttr[i].value + "'";
}
// use innerHTML to get the contents of the table, then close the tag
tableString += firstTable.innerHTML + "</" +
firstTable.nodeName.toLowerCase() + ">";
// table string will have the appropriate content
You can see this in action in a short demo.
The pertinent things to learn are:
getElementsByTagName - get DOM elements by their tag name
attributes - a DOM property that gets an attributes array
innerHTML - gets a string of the HTML inside any DOM object
nodeName - gets the name of any DOM object
If you get into using a framework, jquery's .html() method and the getAttributes plugin would potentially also be helpful

Try following code...
<html>
<head>
<script type="text/javascript">
function sample_function(){
alert(document.getElementById('div_first').innerHTML);
}
</script>
</head>
<body>
<div id="div_first">
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table></div>
<button onclick="sample_function()">Click Here</button>
</body>
</html>

Related

How Do I Convert an HTML String to a Table?

I have a table body object stored as a string. I've tried setting an HTML table using javascript to be that string as follows (the {{}} are because I'm using Flask to get the string):
Way 1:
document.getElementsByTagName("tbody")[0].outerHTML= "{{tbody_string }}";
Way 2:
document.getElementsByTagName("table")[0].outerHTML = '<table>' + "{{tbody_string }}" + '</table>'
Way 3:
document.getElementsByTagName("table")[0].innerHTML = "{{tbody_string}}";
None of these is working. Instead, the table is created and is storing tbody_string as actual text content instead of treating it as html. I've used these sort of structures and flask variables with other HTML elements such as input and it works fine, but it's not seeming to work with table. Thoughts?
Extra Info:
The string looks like this:
'<tbody> <tr> <td>Name</td> <td> <input type="text" name="parameters_name" id="name" class="form-control"> </td> </tr> </tbody>'
The outer quotes are simply shown here to indicate it's a string.
Jinga2 is probably escaping your html when you render it with {{tbody_string}}. You can tell it not to do that with {{tbody_string|safe}}.
Ultimately you can get rid of your "javascript ways" entirely and just render it directly with Jinja2.
Also...please note that if there is any user editable data in your tbody_string, you'll want to take the necessary precautions to avoid creating a security loophole.
Here is javascript code for table
var body = document.getElementsByTagName("body")[0];
var ourTable = document.createElement("table");
var ourTableBody = document.createElement("tbody");
for (var i = 0; i < 4; i++) {
var row = document.createElement("tr");
for (var j = 0; j <2; j++) {
var cell = document.createElement("td");
var cellText = document.createTextNode("cell in row "+i+", column "+j);
cell.appendChild(cellText);
row.appendChild(cell);
}
ourTableBody.appendChild(row);
}
ourTable.appendChild(ourTableBody);
body.appendChild(ourTable);
ourTable.setAttribute("border", "2");
If your table body object stored as a string (aka tbody_string) is a string that goes something like tbody_string = "<table><tr><th>table</th></td></table>"
Way 3 should work fine
<html>
<body>
<table>
<tr>
<th>Replace this table</th>
</tr>
</table>
</body>
<script lang="javascript">
const tbody_string = `
<table>
<tr>
<th>Table</th>
</tr>
<tr>
<td>this is replaced table</td>
</tr>
</table>`;
document.getElementsByTagName('table')[0].innerHTML = tbody_string;
</script>
</html>
However, if your tbody_string isn't HTML markup text but something else.
you'll need to convert it to HTML as text somehow. if it's a DOM element object, the following code should work:
document.getElementsByTagName('table')[0].innerHTML = table_dom.innerHTML

jQuery how to remove dynamically appended rows?

If I append rows to my table like this:
$('#tbody_upload').append('<tr id="' + data.originalFiles[counter].name + '"><td>' + 'Uploading...' + '</td><td></td><td></td><td></td></tr>');
how can I remove it from another event?
$('#' + this.name).remove();
that function doesn't work, also appended items don't appear in source of the page.
If you want remove the element that triggers the event to be removed (as appears from this.name) you can simply do
$(this).remove();
Maybe you should name your table and then with a selector select the body and first errase it and then append data so every time you get new data, the table deletes the old data and puts the new one.
<table id="yourtableName" border="1" class="hoverTable">
<thead>
</thead>
<tbody>
</tbody>
</table>
var gridBody = your tr code;
$('#yourtableName tbody').empty().append(gridBody);

get jsonArray from table

I have a table and need to build json array. I need value from 1 and 4 column of table.
HTML
<table class="table table-striped" id="development_mapping">
<thead>
<tr>
<th>Visual Feature</th>
<th>Step</th>
<th>Output</th>
<th>Data Feature</th>
</tr>
</thead>
<tbody>
<tr><td>color</td>
<td><select id="sss"><option data-id="528092be144b4fbf65893404" selected="selected">first-step</option><option data-id="52809373144b4fbf6589340c">kmeans</option></select></td>
<td><select id="ooo"><option data-id="output" selected="selected">output</option></select></td>
<td><input id="value1" class="feature-execution"value="id"></td></tr></tbody>
</table>
Here is my solution, a function to made an json array from table
JAVASCRIPT
var jsonArray = {};
$('#development_mapping').find('tr').each(function () {
var name = $(this).find('td:first').text();
jsonArray[name] = {
variable : $(this).find('td:eq(3)').text()
};
});
I have done, but not understand, why I get " " from value of 4 column. I mean, why variable in variable is always getting " "
This is my DEMO
Your selector: $('#development_mapping').find('tr') is selecting all <tr> tags in the table. Even the one in the <thead>! The <thead> doesn't have <td> tags, so that's where the " " is coming from.
Try this:
$('#development_mapping').find('tbody tr').each(function () {
var name = $(this).find('td:first').text();
jsonArray[name] = {
variable : $(this).find('td:eq(3)').text()
};
});
You are using .text() but there is no actual text in your 3rd td tag.
try this maybe?
variable : $(this).find('td:eq(3) input').val()
There are 2 problems with your code.
Remove the surrounding <tr> in your table head definition.
Use this to access input value
variable: $(this).find('td:eq(3) > input').first().val()
$.find() will return a collection and you'll need to get the first object of the collection for further use. Plus, you'll need to search for input inside the cell, not the cell itself.
Here is the working fiddle: http://jsfiddle.net/toshkaexe/7q3KP/

JQuery: Find (the index of) a row with a specific data attribute value

I am trying to append a string, myoutput, right after a specific row in a table similar to this one:
<table>
<tr data-my_id='1'> <td> content </td> </tr>
<tr data-my_id='2' data-my_other_id='1' > <td> content </td> </tr>
<tr data-my_id='3' data-my_other_id='2' > <td> content </td> </tr>
</table>
So let's say I want to append my output string after the tr with data-my_other_id='2'
(note that in my code, my_other_id = 2 already )
I am trying to accomplish it doing this:
var want = $("tr").find("[data-my_other_id='" + my_other_id + "']").index();
after finding the index, I want to append my output strhing to this row...
$(want).insertAfter(...?);
Also... I noticed whenever I do
alert( want = $("tr").find("[data-my_other_id='" + my_other_id + "']").length)
I get 0 ...
Help please and let me know if my question is not clear enough so I can explain better.
I'm assuming you want to update the content rather than append, but it doesn't really change anything. I don't think you want to use find() that way. Try something like:
var $row = $('tr[data-my_other_id="' + id + '"]');
// should be the index of the tr in the <table>
// this may not be a good idea though - what if you add a header row later?
var index = row.index() + 1; // if you want 1-based indices
$row.find("td").text("I am row #" + index);
This is because find will no search siblings, only children. Try attaching your search to table.
html:
<table>
<tr data-my_id='1'> <td> content </td> </tr>
<tr data-my_id='2' data-my_other_id='1' > <td> content </td> </tr>
<tr data-my_id='3' data-my_other_id='2' > <td> content </td> </tr>
</table>​
js:
var my_other_id = 2;
alert( $("table").find("[data-my_other_id='" + my_other_id + "']").length);​
demo: http://jsfiddle.net/gDb3A/
You don't need to use the find method since the data attribute is on the tr itself. Also your use of index is not going to work. Try the following instead.
$("tr[data-my_other_id='" + my_other_id + "']").insertAfter(...?);
find looks for descendents. A TR can not be a descendent of itself.
Try using filter()
$("tr").filter("[data-my_other_id='" + my_other_id + "']").index();
Find in the specific table so it will be faster, you can use this method.
Js:
$('any-button').click(function(){
var id = 23;
var $row = $('.your-class tbody tr[data-id="' + id + '"]');
$row.remove();
});
Html
<table class="table table-striped your-class">
<thead>
<tr>...<tr/>
</thead>
<tbody>
<tr data-id="23">Some text</tr>
<tr data-id="43">Some text</tr>
<tr data-id="43">Some text</tr>
</tbody>
</table>

Setting TD value from previous TD

I have a table that is filled in with values dependant on a previous page
those avlues are filled in with struts apparently
but I'm not very good with all that stuff so is there a simple was I can do something like this, either with HTML only or maybe a small javascript I can put in tha page?
<Table>
<TR>
<TH>ID</TH>
<TD><s:property value="groupID" /><TD> <--Number generated by the page with struts
</TR>
<TR>
<TH>ID Value</TH>
<TD>foobar</TD> <-- the text I want to add in dependant on the number from the previous TD
</TH>
</Table>
so, is there a simple way to go about doing this? HTML, CSS, JavaScript solution maybe?
Given that exact HTML, a simple script like this will do it. But if you don't know JavaScript, you should really learn it so that you understand what you're doing.
<body>
<Table>
<TR>
<TH>ID</TH>
<TD><s:property value="groupID" /><TD>
</TR>
<TR>
<TH>ID Value</TH>
<TD>foobar</TD>
</TR>
</Table>
<!-- The script is here so it won't run until the TABLE has loaded -->
<script type="text/javascript">
// This is a map of the struts values to your values
var valueMap = {
"1": "foo",
"2": "bar",
"3": "baz"
};
// Browser compatibility. Older IE uses 'innerText' instead of 'textContent'
var textContent = ('textContent' in document) ? 'textContent' : 'innerText';
// Get all the TD elements on the page
var tds = document.getElementsByTagName('td');
// Get the text content of the first TD (index 0)
var text = tds[0][textContent];
// Get the value from the map using the text we fetched above
var value = valueMap[text];
// Set the text content of the second TD (index 1) to the mapped value
tds[1][textContent] = value;
</script>
</body>
Assuming you want to place the value 'groupID' (set in the first tr's td) into the second row's td element, then the following jQuery will do the trick:
$(document).ready(function() {
// Scrape the XML out of the TD containing the xml
var tdXml = $('table tr').eq(0).find('td').html();
// Grab the value of the value attribute (groupID)
var value = $(tdXml).attr('value');
// Set this value in the second row's TD
$('table tr').eq(1).find('td').text(value);
}​);​
jsFiddle here

Categories

Resources