首页 > 解决方案 > 如何从 html 内容中删除所有链接

问题描述

假设我有一个 html 内容,例如,

<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>

如何从中删除所有链接。我试过了,

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;

它不返回任何值,而是一个空对象。

标签: javascript

解决方案


您可以使用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>


推荐阅读