[jquery] Replace text inside td using jQuery having td containing other elements

My table is as follows:

<table id='demoTable'>
   <tr>
       <td>8: Tap on APN and Enter <B>www</B>.
           <INPUT id=h150000000000000109743 class=hid value="test value" type=hidden>
           <INPUT id=h250000000000000109743 class=hid1 value="26,222,98,10,50000000000000109744,T,~25,221,99,10,,T,www" type="hidden">
       </td>
   </tr>
</table>

I want to change the text only 8: Tap on APN and Enter <B>www</B>.
without affecting the hidden fields

I am trying jQuery but not finding the solution

function changeText() {
    $("#demoTable td").each(function () {
        for (var i = 0; i < $(this).children.length; i++) {
            alert($(this).children(i).val());
        }
        // alert($(this).html());
        // $(this).text("hello");
        // alert($(this).html());
    });
}

This question is related to jquery html

The answer is


A bit late to the party, but JQuery change inner text but preserve html has at least one approach not mentioned here:

var $td = $("#demoTable td");
$td.html($td.html().replace('Tap on APN and Enter', 'new text'));

Without fixing the text, you could use (snother)[https://stackoverflow.com/a/37828788/1587329]:

var $a = $('#demoTable td');
var inner = '';
$a.children.html().each(function() {
    inner = inner + this.outerHTML;
});
$a.html('New text' + inner);

How about:

function changeText() {
    $("#demoTable td").each(function () {
       $(this).html().replace("8: Tap on APN and Enter <B>www</B>", "");
    }
}

Wrap your to be deleted contents within a ptag, then you can do something like this:

$(function(){
  $("td").click(function(){ console.log($("td").find("p"));
    $("td").find("p").remove();    });
});

FIDDLE DEMO: http://jsfiddle.net/y3p2F/


$('#demoTable td').contents().each(function() {
    if (this.nodeType === 3) {
        this.textContent
        ? this.textContent = 'The text has been '
        : this.innerText  = 'The text has been '
    } else {
        this.innerHTML = 'changed';
        return false;
    }
})

http://jsfiddle.net/YSAjU/


Remove the textnode, and replace the <b> tag with whatever you need without ever touching the inputs :

$('#demoTable').find('tr > td').contents().filter(function() {
    return this.nodeType===3;
}).remove().end().end()
  .find('b').replaceWith($('<span />', {text: 'Hello Kitty'}));

FIDDLE