简体   繁体   中英

how to add a string in a span dynamically in <td>

I am trying to add * sign in red color in span tag dynamically.

        <tr>
            <td class="tftable">First Name  </td> <span> </span>
            <td class="tftable">Last Name </td> 
            <td class="tftable">ID </td>
            <td class="tftable">Department </td>
        </tr>

In script section I am trying to add

   var value = $('.tftable span').text("*");
  value.addClass("red");

In css

.red
{
color:red;
}

But i am not getting * sign dynamically near my label.

Here you can add * in all span dynamically.

Check this example it may helps you.

 $(document).ready(function() { $(".tftable span").addClass("red").html("*"); }); 
 .red {color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td class="tftable">First Name <span></span></td> <td class="tftable">Last Name <span></span></td> <td class="tftable">ID <span></span></td> <td class="tftable">Department <span></span></td> </tr> </table> 

Try this

<tr>
    <td class="tftable">First Name  <span> </span></td> 
    <td class="tftable">Last Name <span> </span></td> 
    <td class="tftable">ID <span> </span></td>
    <td class="tftable">Department <span> </span></td>
</tr>

Here you go with the solution https://jsfiddle.net/w1un7sw8/

  var value = $('.tftable > span').html("*"); value.addClass("red"); 
 .red { color:red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td class="tftable">First Name <span> </span></td> <td class="tftable">Last Name </td> <td class="tftable">ID </td> <td class="tftable">Department </td> </tr> </table> 

Mistake was closing tag of td . You should close the td tag after span closing tag.

yes as @Prasanth Ravi answered.... you have to put span inside the 'td' and if you want to give star to specific ones then give class to span and select that class in jquery EXAMPLE:-

<tr>
   <td class="tftable">First Name  <span class="star"> </span></td> 
   <td class="tftable">Last Name <span> </span></td> 
   <td class="tftable">ID <span class="star"> </span></td>
   <td class="tftable">Department <span> </span></td>
</tr>

and the script

var value = $('.star').text("*");
value.addClass("red");

Solved using CSS only. Assumes that all descendants of tftable class that are span elements are going to be asterisks.

.tftable span:before {
  content:'*';
  color:red;
}

Try this,

$('table tr td:first-child').append("<span class='red'>*</span>");

Hope helps,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM