1

I have a variable named MYCELL which is a reference to a td inside a table.

the td looks as follows

   <td>
       abc
       <a href="#" class=".myLinkClass">edit</a>
   </td>

Right now i wish to replace that string abc with def but keep the link. I thought i could use the following code:

        MYCELL.not(".myLinkClass").empty();
        MYCELL.append("def");

But the empty() clears the entire cell. Based on this link i opted to use a selector inside my .not() statement

        MYCELL.not(MYCELL.find(".myLinkClass")).empty();

Any idea on how to empty (including other html-tags) everything in my td without removing any links (<a href>) or any elements with the class .myLinkClass ?

Thank you for your time

User999999
  • 2,500
  • 7
  • 37
  • 63
  • Possible duplicate of http://stackoverflow.com/questions/6156470/jquery-setting-an-elements-text-only-without-removing-other-element-anchor – SSA Aug 28 '14 at 09:27
  • @SSA not quite. In the solution offered the textvalue is always the last child. In my case my `td`can contain many things (including other html-tags\elements) which would have to be removed aswell. The problem isn't limited to simply replacing the text – User999999 Aug 28 '14 at 09:31

1 Answers1

3

You need to use contents() to ensure you can select text nodes as well:

MYCELL.contents().filter(function() {
    return !$(this).is("a"); // Only select nodes where are not <a> tags
}).remove(); // Use .remove instead

jsFiddle

Matt
  • 74,352
  • 26
  • 153
  • 180
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176