How can I get access to the old Node and replace it?
My XHTML has this structure:
<table id="output">
<tr>
<td>Sometext</td>
<td>...</td>
<td>...<td>
</tr>
<tr class="CLASSNAME">
<td class="ElemKat">text</td>
<td class="ELEM">...</td>
<td class="EL">...</td>
</tr>
<tr class="CLASSNAME">
<td class="ElemKat">text2</td>
<td class="ELEM">s</td>
<td class="EL">sss</td>
</tr>
</table>
I have so many classes, because the elements are create dynamically and so the IDs are not a variant.
And the function, in which the error shows up (error as a comment):
var sort=function(cmpFunc) {
var table=document.getElementById("output");
var kat=document.getElementsByClassName("ElemKat");
var elem_kat=new Array();
for(var i=0; i<kat.length; i++) {
elem_kat.push(kat[i]);
}
var elem_kat_old=new Array();
elem_kat_old=elem_kat;
elem_kat.sort(cmpFunc);
for(var j=0; j<elem_kat.length; j++) {
//table=elem_kat_old[j].parentNode; ->No error,but no change in the output
table.replaceChild(elem_kat[j],elem_kat_old[j]); //Node was not found
}
}
Instead of elem_kat_old = elem_kat;, try this:
elem_kat_old = elem_kat.slice(0)
Assigning an array to another array makes it so that whatever you do to one array, happens to the other array. This isn't quite assignment by reference, but I am not 100% sure of the proper Javascript term for it.
Related
I am trying to get the information from my table td's, using javascript. How can i achieve this? I have tried and failed, because i do not exactly understand the JS. So far, i have managed to get one of them to work, which is 'id' but thats just getting info from the db directly, the td values ive been unable to.
echoing the vals in my php update page shows the id val being passed successfully, but none others.
EDIT
Per your last comment I can recommend you use an event listener on all <td> tags and this way you can just get the relevant text of the specific <td> that the user clicked:
var tds = document.querySelectorAll('td');
for (var i = 0; i < tds.length; i++) {
var td = tds[i];
td.addEventListener('click', function(){
console.log(this.innerText)
});
}
<table>
<tr>
<td class="awb">I am the first awb</td>
<td class="awb">I am the second awb</td>
</tr>
<tr>
<td class="differentClass">I am the first differentClass</td>
<td class="differentClass">I am the second differentClass</td>
</tr>
</table>
You are approaching this all wrong...
Instead of this:
var awbno = String(tr.querySelector(".awb").innerHTML);
Do this:
var awbno = document.querySelector(".awb").innerHTML;
Here is a snippet:
var awbno = document.querySelector(".awb").innerHTML;
console.log(awbno);
<table>
<tr>
<td class="awb">Test Text inside a td tag</td>
</tr>
</table>
in order to get the contents of any element using class
let value = document.querySelector('.className').innerHTML;
in order to get the contents of a specific TD
let value = document.querySelector('td.className');
Recently I was asked to write some plain ol JS, that would iterate over a static html table, and allow me to sort the data therein respectively to the column. The idea I have currently is something that loops over the rows, getting the cells data. But I feel there has to be something I am overlooking. I feel I can optimize what I have thus far even further. I'm not really big on loops in loops, and the person who asked me this question is convinced it's possible as well. But I'm a little stumped thinking I can whittle it down further.
which what I have thus far is.
let table = document.getElementById( "table" );
let arr = [];
for(let i=1; i < table.rows.length; i++) {
let obj = {};
for(let j=0; j < table.rows[j].cells.length; j++) {
obj[j] = table.rows[i].cells[j].innerText;
}
arr.push(obj);
}
console.log(arr);
Heres the HTML for reference:
<table id="table">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>555</td>
<td>Mike</td>
<td>25</td>
</tr>
<tr>
<td>963</td>
<td>Christy</td>
<td>23</td>
</tr>
<tr>
<td>42</td>
<td>Bobby</td>
<td>22</td>
</tr>
</table>
You are using bubble sort, Use quick sort to make it even faster
Title might be a bit confusing, but this is the best I could come up with.
I need to find all tr elements which contains td elements matching the filter criteria provided.
Here is my sample,
<tr class="row" id="1">
<td class="philips">PHILIPS</td>
<td class="h4">H4</td>
<td class="lamp">Lamp<td>
</tr>
<tr class="row" id="2">
<td class="philips">PHILIPS</td>
<td class="h5">H5</td>
<td class="bulb">Bulb<td>
</tr>
<tr class="row" id="3">
<td class="neglin">NEGLIN</td>
<td class="w5w">W5W</td>
<td class="tube">Tube<td>
</tr>
<tr class="row" id="4">
<td class="philips">PHILIPS</td>
<td class="h4">H4</td>
<td class="bulb">Bulb<td>
</tr>
<tr class="row" id="5">
<td class="osram">OSRAM</td>
<td class="hb3">HB3</td>
<td class="tube">Tube<td>
</tr>
<tr class="row" id="6">
<td class="neglin">NEGLIN</td>
<td class="w5w">W5W</td>
<td class="lamp">Lamp<td>
</tr>
If I pass filter[0] as 'phillips', the result return tr with id
1
2 and
4
Then if I pass second filter; filter[1] as 'h4', the result should be filtered down to
1 and
4
I have tried this question.
Which has this answer.
$('tr')
.has('td:nth-child(1):contains("Audi")')
.has('td:nth-child(2):contains("red")')
.doSomeThing();
But, I want my filters to be applied dynamically. How would I be able to insert a 3rd has function?
I don't want to go the if-else or switch-case way, if this is possible with out them.
You can try this.
<script type="text/javascript">
$(document).ready(function () {
var result = filter([".philips", ".h4"]);
alert(result);
var result_2 = filter([".philips"]);
alert(result_2);
});
function filter(params) {
var select = "tr";
for (var i = 0; i < params.length; i++) {
select += ":has(" + params[i] + ")";
}
return $(select).map(
function () {
return $(this).attr('id');
}
).get();
}
</script>
if you have an array of filters needed, iterate that array and pass the filter string to the has?
var filters = ['PHILIPS', 'H4', 'Bulb']
var result = $('tr');
for(var i = 0; i < filters.length; i++){
var nchild = i+1;
result = result.has('td:nth-child('+nchild+'):contains("+'filters[i]'+")');
}
edit to your needs of course, but this way you can take user input, compile that into the needed array and then iterate whatever is in the array to filter down results.
You should wrap the $.has() into a separate function (I've just used jquery's easy extensions supports) which will expose the usage as a composite function chain via javascript's syntax...
$( document ).ready(function() {
$('tr')
.nthFilter('td:nth-child(1):contains("PHILIPS")')
.nthFilter('td:nth-child(2):contains("H4")')
.nthFilter('td:nth-child(3):contains("Bulb")')
.css("background-color", "red");
});
jQuery.fn.extend({
nthFilter: function(filter) {
return $(this).has(filter);
}
});
I've put together a small jsfiddle for you to fiddle with :)
You can supply your filter as a string:
var filter = ".philips, .h4";
$("tr").has("td").has(filter).map(function() { return this.id; });
// returns ["1", "2", "4"]
and if you want the elements then obviously leave the map off:
$("tr").has("td").has(filter);
// returns array of <tr>
Edit: Just noticed you want recursive filtering so change the filter to use sibling selector ~.
var filter = ".philips ~ .h4";
// returns ["1", "4"]
So if you want a third level then just:
var filter = ".philips ~ .h4 ~ .bulb";
// returns ["4"]
I am trying to use java-script to export html data into excel. The funny thing is that it DOES work when I use getElementsByTagName instead of getElementById. However, I need to pinpoint id elements and thus 'getElementById' is what I need (I guess). When I debug the below code in IE it gives me:
Object doesn't support property or method 'getElementsById'
Here is what I've got:
HTML (as an idea only):
<body>
<table>
<tr>
<td>content 1</td>
<td>content 2</td>
<td id="R">content I need</td>
<td>some other content</td>
</tr>
</table>
</body>
and accompanying JS
<script type="text/javascript">
function write_to_excel()
{
str="";
var mytable = document.getElementById("R")[0];
var row_Count = mytable.rows.length;
var col_Count = mytable.getElementById("R")[0].getElementById("R").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
for(var i=0; i < row_Count ; i++)
{
for(var j=0; j < col_Count; j++)
{
str= mytable.getElementById("R")[i].getElementById("R")[j].innerHTML;
ExcelSheet.ActiveSheet.Cells(i+1,j+1).Value = str;
}
}
}
</script>
I have the feeling - it's trifle but ... Thanks in advance!)
The getElementById method returns a single DOM element (if you have more than one HTML element with the same ID then your page is buggy but browsers won't complain because 10 years ago it was a common bug that lots of people make). As such the statement:
document.getElementById("R")[0]
Makes no sense whatsoever. Instead, what you want is:
var myTD = document.getElementById("R");
If you have a page structure like this:
<table id='T'>
<tr>
<td>content 1</td>
<td>content 2</td>
<td>content I need</td>
<td>some other content</td>
</tr>
</table>
And want to iterate each column in each row, you'd do it like this:
var mytable = document.getElementById("T");
var table_rows = mytable.getElementsByTagName('tr');
for (var row=0;row<table_rows.length;row++) {
var row_columns = table_rows[row].getElementsByTagName('td');
for (var col=0;col<row_columns.length;col++) {
var item = row_columns[col];
// process item here
}
}
See the documentation of HTMLElement for more info on how to navigate the DOM: https://developer.mozilla.org/en/docs/Web/API/Element
Full documentation of the DOM API: https://developer.mozilla.org/en/docs/DOM
You may also check out the relevant docs on MSDN instead of MDN for IE specific stuff but I prefer MDN because it documents the compatibility level (what other browsers implement a feature) of the API.
IDs must be unique.
Therefore, the function you're looking for is called getElementById (singular)
I have an HTML table with combined row td's, or how to say, I don't know how to express myself (I am not so good at English), so I show it! This is my table:
<table border="1">
<thead>
<tr>
<th>line</th>
<th>value1</th>
<th>value2</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">1</td>
<td>1.1</td>
<td>1.2</td>
</tr>
<tr>
<td>1.3</td>
<td>1.4</td>
</tr>
<tr>
<td rowspan="2">2</td>
<td>2.1</td>
<td>2.2</td>
</tr>
<tr>
<td>2.3</td>
<td>2.4</td>
</tr>
</tbody>
</table>
(you can check it here)
I want to convert this table to a JSON variable by jquery or javascript.
How should it look like, and how should I do it? Thank you, if you can help me!
if you want to convert only text use this one :
var array = [];
$('table').find('thead tr').each(function(){
$(this).children('th').each(function(){
array.push($(this).text());
})
}).end().find('tbody tr').each(function(){
$(this).children('td').each(function(){
array.push($(this).text());
})
})
var json = JSON.stringify(array);
To make a somehow representation of your table made no problem to me, but the problem is how to parse it back to HTML! Here a JSON with the first 6 tags:
{"table":{"border":1,"thead":{"th":{"textContent":"line","tr":"textContent":"value1",...}}}}}...
OR for better understanding:
{"tag":"table","border":1,"child":{"tag":"thead","child":{"tag":"th","textContent":"line",
"child":{"tag":"tr","textContent":"value1","child":...}}}}...
Closing tags are included.
For further explanations I need to know whether your table is a string or part of the DOM.
I belive this is what you want:
var jsonTable = {};
// add a new array property named: "columns"
$('table').find('thead tr').each(function() {
jsonTable.columns = $(this).find('th').text();
};
// now add a new array property which contains your rows: "rows"
$('table').find('tbody tr').each(function() {
var row = {};
// add data by colum names derived from "tbody"
for(var i = 0; i < jsonTable.columnsl.length; i++) {
row[ col ] = $(this).find('td').eq( i ).text();
}
// push it all to the results..
jsonTable.rows.push( row );
};
alert(JSON.stringify(jsonTable));
I think there should be some corrections, but this is it I think.