0

I'm trying to extract a text from td as discussed here Replacing a part of text inside a td

$('.my-table tr').each(function() {

     var contact = $(this).find('td').eq(1)[0].childNodes[0].nodeValue;
     $(this).find('td').eq(1).contents()[0].data = contact.substring(0,10);
});

But contact.substring(0,10); doesn't seem to work and it just shows empty.

How can i fix this?

Community
  • 1
  • 1
user1184100
  • 6,742
  • 29
  • 80
  • 121

3 Answers3

1

Try this:

$('.my-table tr').each(function() {

     var contact = $.trim($(this).find('td').eq(1)[0].childNodes[0].nodeValue);
     if(contact != '')
     {
         var value = contact.substring(0,10);
         alert(value);
         $(this).find('td').eq(1).contents()[0].data = contact.substring(0,10);
     }
});

What is the alert value you are getting?? or are you getting any alerts??

palaѕн
  • 72,112
  • 17
  • 116
  • 136
1

Don't use .eq(1)[0], but just .get(0) to get plain DOM nodes. Also, don't use two different ways of obtaining the same text node, but only one and store it in a variable. Let's check what has happened:

$('.my-table tr').each(function() {

     var cell = $('td', this);
     if (!cell.length)
         return alert("Could not find a table cell");

     var el = cell.get(0);
     if (!el) alert("Could not get first element"); // Won't happen if length was >0

     if (!el.childNodes.length)
         return alert("Cell is empty!");

     var text = el.childNodes[0];
     if (cell.contents()[0] != text) alert("different firstChilds???"); // Won't happen
     if (text.nodeType != 3)
         return alert("the first child node is not a text node!");

     var contact = text.nodeValue;
     if (text.data != contact) alert("different contents???"); // Won't happen
     if (typeof contact != "string") alert("content is no string"); // Won't happen

     var newcontact = contact.substring(0,10);
     alert('"'+contact+'" was changed to "'+newcontact+'"');
     text.data = newcontact;
});

(Demo at jsfiddle.net)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

First of all does contact holds what you need? I mean did you console.log contact value?

If contact is ok then try something like this:

var contact = new String($(this).find('td').eq(1)[0].childNodes[0].nodeValue);
Jevgeni Smirnov
  • 3,787
  • 5
  • 33
  • 50