0

So, I have a table and there is a colum called value with different numbers that varies from 0 to 2.

<column>Values<column>
<td>0</td>
<td>2</td>
<td>0</td>

Yes, I know that something like does not exist, it was just for sake of example. But the real question is, how can I with help of jquery find those numbers and replace it with something else.. for example

    if(td == 1){
       replace 1 with "Hello"
    }
Harugawa
  • 539
  • 5
  • 19

4 Answers4

1

Use contains() to get td which have similar text and replace text using .text()

$("td:contains('1')").text("hello");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
Jayesh Chitroda
  • 4,987
  • 13
  • 18
0

Can you give your elements Id's? This may make your code more readable and maintainable, and will remove the dependency between the value you are trying to replace and the code that is looking for it.

If you can use Id's, then you can use jQuery selectors to get hold of the element and then, depending on the element type, set the text or innerHtml to your required values.

Foe example;

$( document ).ready(function() {
    $('#col1').text('hello');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td id="col1">1</td>
    <td id="col2">2</td>
    <td id="col3">3</td>
  </tr>
</table>

or JsFiddle.net

Mark Cooper
  • 6,738
  • 5
  • 54
  • 92
0

Well, it depends...

If you are refering to ALL the content of the cell as a numeric value, you can do this (in JS)

if(Number($(td).html().trim()) == number_to_replace){
    $(td).html(text_for_replacement);
}

where "td" could referer to the cell as a DOM variable or could be a string selector

hrkns
  • 1
  • 2
0

Use :contains() pseudo-class to select all td which contains 1 and then use text() with callback to check content is exactly 1 and update.

$('td:contains(1)').text(function(i, v) {
  return $.trim(v) == '1' ? 'hello' : v;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>11</td>
  </tr>
</table>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188