Home > Software engineering >  Remove strong tag inside hyperlink with JQuery
Remove strong tag inside hyperlink with JQuery

Time:12-16

I'm trying to remove the tag inside this HTML but can't seem to work out how:

<p>This is his: “<u><a href="https://secure.nm.com/"><strong>Fourth and Final Prediction</strong></a></u>.”</p>

I've tried this but it's not working - where am I going wrong?

$("a:has(strong)").each(function() {
$(this).replaceWith($(this).children());

})

CodePudding user response:

There are many ways to accomplish that.

If you want to remove all of the html you can replace the HTML with the text.

$(this).html($(this).text());

If you want to replace the HTML with everything in strong you can replace the HTML with the strong HTML:

  $(this).html($(this).find("strong").html())

$("a:has(strong)").each(function() {
  $(this).html($(this).text());
  //$(this).html($(this).find("strong").html())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>This is his: “<u><a href="https://secure.nm.com/"><strong>Fourth and Final Prediction</strong></a></u>.”</p>

CodePudding user response:

You can use the jQuery unwrap() function:

$('a strong').contents().unwrap();

Demo:

$('a strong').contents().unwrap();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>This is his: “<u><a href="https://secure.nm.com/"><strong>Fourth and Final Prediction</strong></a></u>.”</p>

<p>This is his: “<u><a href="https://secure.nm.com/"><strong>Fourth and Final Prediction</strong></a></u>.”</p>

<p>This is his: “<u><a href="https://secure.nm.com/"><strong>Fourth and Final Prediction</strong></a></u>.”</p>

The .unwrap() method removes the element's parent and returns the unwrapped content.

  • Related