Skip to content
Advertisement

How to remove all links from an html content

Say I have an html content like,

<p id="p_content">
Test

<a href='https://google.com'>google</a>

Test

<a href='https://example.co'>example</a>

Hello

<a href='https://Test.com'>test</a>

</p>

How to remove all links from this. I tried like,

var content = document.querySelector('#p_content');
var a = content.querySelectorAll('a');
var texts = [].slice.call(a).map(function(val){
   return val.innerHTML;
});
console.log(texts);
document.querySelector('#p_content').innerHTML = texts;

It doesnt return any value but an empty object.

Advertisement

Answer

You can use remove()

document.querySelectorAll('#p_content a').forEach(el => el.remove())
<p id="p_content">
  Test
  <a href='https://google.com'>google</a>
  Test
  <a href='https://example.co'>example</a>
  Hello
  <a href='https://Test.com'>test</a>
</p>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement