Javascript - get all table -> tr values - javascript

<table>
<tr><td>foo</td></tr>
<tr><td>bar</td></tr>
<tr><td>abc#yahoo.com</td></tr>
</table>
Can anybody tell me how to write a Javascript line to only grab the email address in the table below, I've been searching a lot, but all I come across is tutorials which use "id" in either table on in td .. I want to do it without having an id .. please help

var rows = document.getElementsByTagName("table")[0].rows;
var last = rows[rows.length - 1];
var cell = last.cells[0];
var value = cell.innerHTML
Try it yourself here: http://jsfiddle.net/ReyNx/.
Obviously you'll have to change document.getElementsByTagName("table")[0] to appropriately match your table
If you're using jQuery it's easier:
var value = $('table tr:last td').text();
For more info, see the MDN DOM reference, which shows you which properties are available on which elements to traverse the DOM.

No jQuery, innerHtml or other evil / heavy functions, just plain old JavaScript:
// Get the first table in the document.
var table = document.getElementsByTagName('table')[0];
// Get the third row of this table (0-index 3rd = 2)
var emailRow = table.rows[2];
// Get this element's content.
var emailContent = emailRow.firstChild.textContent;
You could write it in 1 line:
var emailContent = document.getElementsByTagName('table')[0].rows[2].firstChild.textContent;
If you want to find all email addresses in a table:
var emails = [];
var table = document.getElementsByTagName('table')[0];
var rows = table.rows;
for (var i = 0; i < rows.length; i++) {
var rowText = rows[i].firstChild.textContent;
if (~rowText.indexOf('#')) { // If the content of the row contains a '#' character (This could be replaced with a regex check)
// Also, I personally prefer to use '~' over '> -1' for indexOf(), but both would work.
emails.push(rowText);
}
}
console.log(emails);
Working example

If like me you want to get the text from all the first column items in all the tables on the page then use this.
jQuery('table tr td').each( function( cmp ) {
console.log( jQuery(this).text() );
} );

I wanted to extract all emails, but I had more than 1,000 rows and 17 columns/cells.
I used vanilla js, made some adjustments to get my desired output
var table = document.getElementsByTagName("table")[0]; //first table
var rows = table.rows;
//loop through rows
for (var i = 0; i < rows.length; i+=1) {
var emailTr = rows[i];
var emailTd = emailTr.cells[2]; //target third column/cell
var email = emailTd.innerHTML; //get the value
console.log(email + ', ');
var node = document.createElement("span"); // create span element
node.innerHTML = email + ', '; // desired output
document.body.appendChild(node); // display to document body
}

Assuming you're using vanilla Javascript (no libraries such as jQuery), and that this is the only table on the page, you can use the following code to select the third tr in the table, then find out what the td element contains
var table = document.getElementsByTagName("table")[0];
var emailTr = table.rows[2];
var emailTd = emailTr.cells[0];
var email = emailTd.innerHTML;
jQuery would make this easier
var email = $("table").children("tr:eq(2)").children("td").html();

A simple way is to give it a common class. Try:
<table>
<tr><td class="email">foo</td></tr>
<tr><td class="email">bar</td></tr>
<tr><td class="email">abc#yahoo.com</td></tr>
</table>
<script>
function getEmail(){
var email = new Array();
var arr = document.getElementsByClassName('email');
for(var i=0; i< arr.length; i++){
email.push(arr[i].innerHTML);
}
alert(email.join(','));
}
</script>
Demo

This is a solution in case you are using or plan to use jQuery library.
Given the email is always in the third row and first column (like in your example) then you can do as follows:
email = $('table tr:nth-child(3) td:first-child').html();
See working demo

Get all the <tr> elements. Loop through each one and compare the innerHTML against a regex that matches email addresses.
var emailAddresses = [];
var cells = document.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
if (cells[i].innerHTML.match(/yourEmailRegex/g)) {
emailAddresses[emailAddresses.length] = cells[i].innerHTML;
}
}
Find the appropriate regular expression here http://www.regular-expressions.info/email.html

in my case i want fifth column value of last row
var rows = document.getElementsByTagName("tbody")[0].rows;
var last = rows[rows.length - 1];
var cell = last.cells[4];
console.log(cell.textContent);

Related

How to set values in new column with validation from a Named Range?

Following a previous question
I want to classify text entries by adding a tag in the next column.
I could do it using regex but it will take too much time writing all conditions like :
if(String(data[i][0]).match(/acme|brooshire|dillons|target|heb|costco/gi))
{
labValues[i][0]='Supermarket';
}
Instead I created a named list with all stores names (in another sheet).
If an entry matches a term in the list, the next column is set to "Supermarket".
I am using this script below... No bugs but nothing happens when executed !
function tagStore() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange('A2:A655')
var store = range.getValues();
var tag = sheet.getRange('B2:B655');
var tagvalues= tag.getValues();
var storeList= SpreadsheetApp.getActive().getRangeByName("store_list");
for (var i = 0; i<store.length; i++)
{
if(String(store[i][0]).match(storeList))
{
tagvalues[i][0]='Supermarket';
}
}
tag.setValues(tagvalues);
}
Edit:
It is important to use a Regex as the "store" Values are not exactly the same as the "store_list".
Store Values : ["Acme Store", "HEB PLaza", "Dillons Group"...]
Store_List : [acme, heb, dillons...]
Instead of trying to go with the regEx approach there is a more straightforward approach by retrieving the range as a list.
// For a Column
var storeList = SpreadsheetApp.getActive().getRangeByName("store_list").getValues().map(function(r){return r[0];});
// For a Row
var storeList = SpreadsheetApp.getActive().getRangeByName("store_list").getValues()[0];
And then look if the values you are looking for are in this list with indexOf().
Try this:
function tagStore() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange('A2:A655')
var store = range.getValues();
var tag = sheet.getRange('B2:B655');
var tagvalues= tag.getValues();
var storeList= SpreadsheetApp.getActive().getRangeByName("store_list").getValues().map(function(r){return r[0];});//if it's a column
//var storeList=SpreadsheetApp.getActive().getRangeByName("store_list").getValues()[0];//if it's a row
for (var i=0;i<store.length; i++) {
if(storeList.indexOf(store[i][0])!=-1) {
tagvalues[i][0]='Supermarket';
}
}
tag.setValues(tagvalues);
}

Jquery check if data exist as a substring on an html table

Check if data exist on an html table even if it is a substring.
var substring = 'find me'; //substring or data that you wanted to check
var dataExist = [];
$('table#tableID tr').each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
if($(this).text().indexOf(substring) == -1)
dataExist.push(true);
}
});
console.log(dataExist.includes(true))
If you're just trying to figure out if a table has a string anywhere in it, you could simply use indexOf() on myTable.innerText.
var myTable = document.getElementById('myTable');
var exists = myTable.innerHTML.indexOf('find me');
If you want to make sure the exists variable is always a boolean, you can use the below line.
var exists = !! ~ document.getElementById('tableID').innerHTML.indexOf('find me');

join an array of elements to append it to a node

How can I do something like:
var html = [];
var tr = document.createElement('tr');
var tr_two = document.createElement('tr');
var tr_three = document.createElement('tr');
html.push(tr);
html.push(tr_two);
html.push(tr_three);
html.join(''); //This doesnt work
document.getElementById('tbody').appendChild(html);
So I need to join my array in a way that is doable, so I hit the DOM once.
Try:
var tbody = document.getElementById('tbody');
html.forEach(funtion(node) {
tbody.appendChild(node);
});
You are trying to join DOM elements instead strings.
You can use outerHTML to achive what you want.
var html = [];
var tr = document.createElement('tr');
var tr_two = document.createElement('tr');
var tr_three = document.createElement('tr');
html.push(tr.outerHTML);
html.push(tr_two.outerHTML);
html.push(tr_three.outerHTML);
html.join(''); //Now it will work
And to append to DOM use
document.getElementById('tbody').innerHTML += html.join('');
The appendChild() function can only be used with nodes, not strings. To do that with your current code, change it to the following:
var html = [];
var tr = document.createElement('tr').appendChild(document.createTextNode("tr 1"));
var tr_two = document.createElement('tr').appendChild(document.createTextNode("tr 2"));
var tr_three = document.createElement('tr').appendChild(document.createTextNode("tr 3"));
html.push(tr);
html.push(tr_two);
html.push(tr_three);
var tbody = document.getElementById("tbody");
html.forEach(function(elem) {
tbody.appendChild(elem);
})
I've added text nodes to each of the trs created so you can see the difference between each one.
The forEach loop just iterates over each element in array you created, and appends each one at time to the element you specified.
Here's a JSFiddle.

Jquery ID selector doesnt work with a variable

I've read a billion questions like this, but never found an answer yet.
Anyway, when I type
var variableContainingID = "header";
var div = $("#"+variableContainingID);
It returns 'undefined'
But when I type
var variableContainingID = "header";
var div = $('[id^="'+variableContainingID+'"]');
It works fine.
Any ideas why?
UPDATE
var json = '{"divs":['
var children = $(".parent_container > div");
var idArray = [];
var numArray = [];
for (var x=0; x<children.length; x++) {
var eleid = $(children[x]).attr("id");
idArray.push('"'+eleid+'"');
numArray.push(x+1);
}
var idString = idArray.join(",");
var numString = numArray.join(",");
json += idString;
json += '],"number":['+numString+']}';
var obj = JSON.parse(json);
for (x in obj["divs"]) {
var div = $('[id^="'+obj["divs"][x]+'"]');
}
Do you think the double quotes could be throwing it off?
As you wrote in your question:
var div = $("#"+variableContainingID);
var div = $('[id^="'+variableContainingID+'"]');
These two lines are not identical. The first one, will select an element with id of header. The second one,
selects elements that have the specified id with a value beginning exactly with a given string (header).
So if you have an element like this:
<div id="headerHere"></div>
The first one ($("#"+variableContainingID)) can't select it, but the second one ($('[id^="'+variableContainingID+'"]')) can select that element.
This is because you used ^= in your selector. See jQuery API: Attribute Starts With Selector (name^="value").
It's worth to see all attribute selectors in jQuery.
Attribute Selectors in jQuery

How to pass Text parameter to the function in the loop?

Hi I'm stuck I need to pass the Status into the Apply() function. But when I put Apply("+ Status +"); into the for loop it doesn't seem to work. But if Status is equal to some number it works. Please help. Here is my code.
Status is equal to "Complete, Uncomplete".
function querySuccess(tx, results, Type, Status, Amount, Years){
var len = results.rows.length;
var display = "";
display +="<table>";
display +="<tr>";
display +="<td>First Year Rate</td>";
display +="<td>Apply Now</td>";
display +="</tr>";
for (var i=0; i<len; i++){
display +="<tr>";
display +="<td>"+ results.rows.item(i).first_year+"</td>";
display +="<td><input type'button' onClick='Apply();' value='Apply'/></td>";
display +="</tr>";
}
display +="</table>";
}
Try Apply(\""+ Status +"\");. The escaped quotes tells JS that there is a text, otherwise it thinks there are some variables.
You can use single-quotes Apply('"+ Status +"');, but this need some modifications in your code.
if status is a string you need to encapsulate it like this:
display +="onClick=\"Apply('"+ Status +"');\" ";
Note the different usage of single and double quotes
If you Status is string you have to use "" for example "String". In your case this should work:
display +="<td><input type'button' onClick='Apply("'+Status+'");' value='Apply'/></td>";
Number works because they dont need apostrophe and thats why they are processed correctly.
I made simplier example and used your code to show it. Check your JavaScript console to see a result:
http://jsfiddle.net/EE8hN/
check this one.this wil work
display += '<td><input type="button" onClick="Apply('+status+')" value="Apply"/></td>'
function querySuccess(tx, results, Type, Status, Amount, Years){
var len = results.rows.length;
var display = document.createElement('table');
var tr = document.createElement('tr');
var td = document.createElement('td');
var tmpEl;
var tmpTr = tr.cloneNode();
var tmpTd = td.cloneNode();
tmpTd.textContent = "First Year Rate";
tmpTr.appendChild(tmpTd);
tmpTd = td.cloneNode();
tmpTd.textContent = "Apply Now";
tmpTr.appendChild(tmpTd);
display.appendChild(tmpTr);
for (var i=0; i<len; i++){
tmpTr = tr.cloneNode();
tmpTd = td.cloneNode();
tmpTd.textContent = result.rows.item[i].first_year;
tmpTr.appendChild(tmpTd);
tmpEl = document.createElement('input');
tmpEl.type = 'button';
tmpEl.value = 'Apply';
tmpEl.onclick = Apply; // yeah, just like this
tmpTd = td.cloneNode();
tmpTd.appendChild(tmpEl);
tmpTr.appendChild(tmpTd);
}
}

Categories