Вы можете просто сделать копию элементов вне DOM, удалить элементы привязки из них, а затем запросить textContent
:
let container = document.createElement('div');
[...document.getElementsByTagName('p')].forEach(p => container.innerHTML += p.innerHTML);
// remove links
[...container.querySelectorAll('*')].forEach(el => {
if (el.tagName === 'A') el.remove();
})
console.log(container.innerHTML);
document.getElementById('result').innerHTML = container.innerHTML;
<p>This is a <a href="https://www.google.com">first</a> search engine.</p>
<div>Here I have also some text</div>
<p>This is a <b>web browser</b>.</p>
<p>This is another <a href="https://www.bing.com">second</a> search engine.</p>
<div id="result"></div>
Вот в основном то же решение в ECMAScript 5, к которому вы могли бы более привыкнуть:
// create a container element not in the DOM to copy stuff to
var container = document.createElement('div');
// get all paragraph elements
var paras = document.getElementsByTagName('p');
// iterate over each paragraph and add its innerHTML to the container
for (var i = 0; i < paras.length; i++) {
container.innerHTML += paras[i].innerHTML
}
// get all container child elements
var containerChildren = container.querySelectorAll('*');
// iterate over them and remove any links
for (var j = 0; j < containerChildren.length; j++) {
if (containerChildren[j].tagName === 'A') containerChildren[j].remove();
}
console.log(container.innerHTML);
// make the result visible
document.getElementById('result').innerHTML = container.innerHTML;
<p>This is a <a href="https://www.google.com">first</a> search engine.</p>
<div>Here I have also some text</div>
<p>This is a <b>web browser</b>.</p>
<p>This is another <a href="https://www.bing.com">second</a> search engine.</p>
<div id="result"></div>