I have a table where I pull data and add it to an array of arrays. The problems is if one of the table cells is empty it appears in the array as "undefined". I tried using an if the last element is undefined if so using .pop() the element should be removed. I still get undefined elements. Here's my code and live demo
HTML :
<table id="contactlisttable">
<tr>
<th>Name</th>
<th>Title</th>
<th>Phone</th>
</tr>
<tr>
<td class="contactlist contactlistlastfirst">Joey</td>
<td class="contactlist contactlisttitle">webdesigner</td>
<td class="contactlist contactlistphone"></td>
</tr>
<tr>
<td class="contactlist contactlistlastfirst">Anthony</td>
<td class="contactlist contactlisttitle">webdesigner</td>
<td class="contactlist contactlistphone">5555555</td>
</tr>
</table>
//IE9+ compatable solution
$(function(){
var results = [], row;
$('#contactlisttable').find('th, td').each(function(){
if(!this.previousElementSibling){ //New Row?
row = [];
results.push(row);
if($(this) === 'undefined'){//Remove undefined elements
row.pop();
}
}
row.push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)
});
console.log(results);
});
jsFiddle Demo
Instead of doing the conditional statements, just take advantage of your html structure. First select by the table rows, and then iterate the child td or th elements. You can also take advantage of jQuery's text instead of doing the feature detection. jQuery's text will be more reliable.
var results = [];
$('#contactlisttable tr').each(function(){
var row = [];
$(this).find('td,th').each(function(){
row.push($(this).text());
});
results.push(row);
});
console.log(results);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With