Skip to content
Advertisement

How to replace value in td using jquery/php? (wordpress)

I have a html code below (created using a plugin).
I need to change colspan=”6″ to colspan=”4″.
I tried jQuery below, but it doesn’t work…
Would you please help me?

<table class="shop_table">
   <thead>
       <tr><th></tr></th>
   </thead>
   <tbody>
    <tr><td class="aa"></td></tr>
    <tr><td class="bb"></td></tr>
    <tr><td class="cc" colspan="6"></td></tr>
   <tbody>
</table>

$('.shop_table').find('td:last-child').contents().filter(function() {
    return this.nodeType===3;
}).remove().end().end().find('colspan="6"').replaceWith($(('colspan="4"'));

Thank you.

Advertisement

Answer

With the selector [colspan="6"] you can get to each and set a new attribute:

$('.shop_table [colspan="6"]').each(function() {
  this.setAttribute('colspan', '4');
});
console.log($('table').html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="shop_table">
   <thead>
       <tr><th></th></tr>
   </thead>
   <tbody>
    <tr class="aa"><td></td></tr>
    <tr class="bb"><td></td></tr>
    <tr class="cc" colspan="6"><td></td></tr>
   <tbody>
</table>

Or, without jQuery:

for (const elm of document.querySelectorAll('.shop_table [colspan="6"]')) {
  elm.setAttribute('colspan', '4');
}
console.log(document.querySelector('table').innerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="shop_table">
   <thead>
       <tr><th></th></tr>
   </thead>
   <tbody>
    <tr class="aa"><td></td></tr>
    <tr class="bb"><td></td></tr>
    <tr class="cc" colspan="6"><td></td></tr>
   <tbody>
</table>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement