praveenpds
praveenpds

Reputation: 2936

How to loop till text element in table

Problem

I want to collect all table data using javascript and send back to some part of application.

html

<table>
    <tbody>
        <tr>
        <td>
            <span>hello</span>
        </td>
        <td>
            <ul>
                <li>1<span>:2000</span></li>
                <li>2<span>:3000</span></li>
                <li>
                    <span>link</span>
                    <span>
                        <a href=''>failed login</a>
                    </span>
                </li>
            </ul>
        </td>
    </tbody>
</table>

output Expected :


       hello 1 :2000 :3000 link failed login

Thanks in advance.

Upvotes: 0

Views: 50

Answers (2)

Devendra Soni
Devendra Soni

Reputation: 1934

try this

$(document).ready(function() {
    var texts = [];
    $("table tr td").each(function(i, elem) {

        texts.push($.trim($(elem).text()))

    });
    var str = texts.join(':').replace(/(\r\n|\n|\r)/gm, "")
    alert(str);

});

see working example:- http://jsfiddle.net/fL28r/84/

thansks

Upvotes: 1

RobG
RobG

Reputation: 147413

You can use a recursive function like the following. There is no normalisation, you may wish to remove excess whitespace and insert spaces between the text from each element.

// Get the text within an element
// Doesn't do any normalising, returns a string
// of text as found.
function getTextRecursive(element) {
  var text = [];
  var el, els = element.childNodes;

  for (var i=0, iLen=els.length; i<iLen; i++) {
    el = els[i];

    // May need to add other node types here that you don't want the text of
    // Exclude script element content
    if (el.nodeType == 1 && el.tagName && el.tagName.toLowerCase() != 'script') {
      text.push(getTextRecursive(el));

    // If working with XML, add nodeType 4 to get text from CDATA nodes
    } else if (el.nodeType == 3) {

      // Deal with extra whitespace and returns in text here if required
      text.push(el.data);
    }
  }

  // Insert a space between each text string and return
  // a single string
  return text.join(' ');
}

Upvotes: 1

Related Questions