Pradip R.
Pradip R.

Reputation: 450

Replace Text if found in the children of Element using jQuery

I have following HTML being rendered on the page:

<tr>
    <td colspan="100" nowrap="nowrap" class="ms-gb">
        <a href="javascript:" onclick="javascript:ExpCollGroup('0-1_', 'img_0-1_',event, false);return false;">
            <span class="commentcollapse-iconouter">
                <img class="commentcollapse-icon" src="Some Image" alt="collapse" id="img_0-1_" data-themekey="#">
            </span>
            iPad_Category
        </a>
         : AL Mobile 
        <span style="font-weight: lighter; display: inline-block;">(7)
        </span>
    </td>
</tr>

enter image description here

Now my question is: What if I want to remove a keyword iPad_Category with the help of jQuery, what could it be? Additionally, how can I replace such text with the new one? For example,: AL-Mobile should be replaced by AL Mobile, What's the best possible way to implement this with jQuery or JavaScript?

Edit: I cannot remove span tag from the element as it has necessary event bound.

Any help would be much appreciated.

Upvotes: 0

Views: 89

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could get the HTML code of the target element then using replace() method you can replace and remove the parts you want, finally return the new HTML with replaced data and override the original one like :

var new_structure = $("#my-div").html().replace(': AL Mobile', 'AL Mobile').replace('iPad_Category', '');

$("#my-div").html(new_structure);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="my-div">
  <tr>
    <td colspan="100" nowrap="nowrap" class="ms-gb">
      <a href="javascript:" onclick="javascript:ExpCollGroup('0-1_', 'img_0-1_',event, false);return false;">
        <span class="commentcollapse-iconouter">
                <img class="commentcollapse-icon" src="Some Image" alt="collapse" id="img_0-1_" data-themekey="#">
            </span> iPad_Category
      </a>
      : AL Mobile
      <span style="font-weight: lighter; display: inline-block;">(7)
        </span>
    </td>
  </tr>
</table>

Upvotes: 2

Related Questions