0

I have html that looks like this,

<table id="TableAddresses">
    <tbody>
                <tr>
                    <td>
                        string 1
                    </td>
                    <td>
                    <input type="hidden" id='ADDR_843886'
                    <div id='FLAG_843886'>Pending...</div>

                    </td>
                </tr>
                <tr>
                    <td>
                        string 2
                    </td>
                    <td>
                    <input type="hidden" id='ADDR_843886'
                    <div id='FLAG_843886'>Pending...</div>

                    </td>
                </tr>

How do I get all the strings inside of TableAddresses > tbody >tr > td[0]?

EDIT:

I was mistaken in tagging jquery. This is actually a asp.net project.

5 Answers 5

1

An easy way would be to use querySelectorAll

var td = querySelectorAll("#TableAddresses tbody td")[0];

Otherwise you can do

var table = document.getElementById("TableAddresses");
var tbody = table.getElementsByTagName("tbody")[0];
var tr    = tbody.getElementsByTagName("tr")[0];
var td    = tr.getElementsByTagName("td")[0];
// etc
Sign up to request clarification or add additional context in comments.

1 Comment

querySelectorAll() is not backwards compatible. Just a comment.
1

You can try this:

document.getElementById('TableAddresses').firstChild.firstChild.firstChild.innerHTML

or with less legacy support:

document.querySelector('#TableAddresses td').innerHTML

Comments

1

You can use the map method:

var strings = $('#TableAddresses td:first-child').map(function() {
    return $.trim( this.textContent || this.innerText );
}).get(); // ["string 1", "string 2"] 

Alternatively you can read the HTMLTableElement's rows property:

var rows = document.getElementById('TableAddresses').rows, 
    strings = [];

for (var i = 0; i < rows.length; i++) {
    if ( rows[i].cells[0] ) {
       strings.push( rows[i].cells[0].innerHTML );
    }  
}

http://jsfiddle.net/kvyUh/

Comments

0

Using jQuery:

var myString = $('#tableAddress td:first').text()

Cheers!

Comments

0

There's an MDN article on this topic. In a nutshell, you need to traverse your table with standard means, mostly getElementsByTagName, see this jsBin (look in the console).

var table =  document.getElementById("TableAddresses");

var rows = table.getElementsByTagName("tr");
Array.prototype.forEach.call(rows, function(ele, idx) {
  console.log(ele.getElementsByTagName("td")[0].textContent.trim());
});

This snippet traverses each row of your table and outputs the textContent of the first <td> element. Please note that this will most likely not work out of the box on older IE versions iirc, but nothing that can't be shimmed. ;-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.