0

I'm piggy backing off of a previous post that talks specifically about removing a string from inside an element. The code to do that is:

  $this.text( $this.text().replace("text to strip out", "") );

I've successfully stripped out the text "categories: "

FYI: This is a blog page with categories that are dynamically added. HTML structure before I strip out "categories: ":

<container>
   <div class="categories">
     "categories: "  //This is what I strip out with above code
     <a href = "...">Category Name</a> //This is a linked category name
   </div>
</container>

The problem is that when I remove "categories: " it is also stripping out the and leaving me with an unlinked "Category Name"

After the jquery runs html looks like this:

 <container>
   <div class="categories">Category Name</div>
</container>

I need to keep the link active, as I want the ability for the user to click "Category Name" to stay.

Community
  • 1
  • 1
pappley
  • 479
  • 1
  • 4
  • 12

3 Answers3

0

One way to do it, don't know if it's the best way, is to save the anchor element as a javascript variable. Then after you remove the stuff you want to remove, inject that anchor back in.

Leeish
  • 5,203
  • 2
  • 17
  • 45
0

Try this instead...

$("div.categories").each(function() {
    var $this = $(this);
    $this.html($this.html().replace("categories: ", ""));
});
Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
0

To remove a textNode you need to use contents() to retrieve them, then a combination of filter() and remove(), like this:

$('.categories')
    .contents()
    .filter(function() { return this.nodeType == 3; })
    .remove();

Example fiddle

Note this will remove all direct child textNodes. If you want to filter by the text of the node, amend the filter() function accordingly.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339