Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace text inside td using jQuery having td containing other elements

Tags:

html

jquery

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());     }); } 
like image 766
शेखर Avatar asked Dec 11 '12 09:12

शेखर


People also ask

How to change text inside an element using jQuery?

To change text inside an element using jQuery, use the text () method. You can try to run the following code to replace text inside an element:

How to replace only text inside a Div using jQuery?

To replace only text inside a div using jQuery, use the text () method. You can try to run the following code to replace text inside a div:

How to replace strings in HTML with jQuery?

$("#element").text("What's up!"); In a similar way, we can replace the whole HTML content by using the html function: By using jQuery in combination of JavaScript functions we are able to replace strings in elements, texts and even JavaScript variables.

How to replace text with regular expression in jQuery?

Use the jQuery text function to get its text. Replace the text using replace. Pass the result of this process to the text function to the same element. The replace () admits two parameters. The first is the value we want to replace (or the regular expression) and the second is the new string that will replace it.


2 Answers

Using text nodes in jquery is a particularly delicate endeavour and most operations are made to skip them altogether.

Instead of going through the trouble of carefully avoiding the wrong nodes, why not just wrap whatever you need to replace inside a <span> for instance:

<td><span class="replaceme">8: Tap on APN and Enter <B>www</B>.</span></td> 

Then:

$('.replaceme').html('Whatever <b>HTML</b> you want here.'); 
like image 158
Ja͢ck Avatar answered Oct 01 '22 08:10

Ja͢ck


$('#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/

like image 31
undefined Avatar answered Oct 01 '22 10:10

undefined