Here's what I'm dealing with; I don't have control of it.
<div id="foo">
<div>etc.</div>
<div>etc.</div>
(foobar) (<a href="example.com">barfoo</a>) | (<a href="stackoverflow.com">lorem</a>) (ipsum)
<ul>
<li>etc.</li>
<li>etc.</li>
<li>etc.</li>
<li>etc.</li>
</ul>
(foobar) (<a href="example.com">barfoo</a>) | (<a href="stackoverflow.com">lorem</a>) (ipsum)
<div>etc.</div>
</div>
How can I get (foobar) (<a href="example.com">barfoo</a>) | (<a href="stackoverflow.com">lorem</a>) (ipsum)
out of #foo
?
CodePudding user response:
You could use a regex that is designed to match anything within brackets to extract the non-wrapped tags:
const targetElement = document.getElementById("foo")
const result = targetElement.innerHTML.match(/(\(. \))/gm)
console.log(result)
<div id="foo">
<div>etc.</div>
<div>etc.</div>
(foobar) (<a href="example.com">barfoo</a>) | (<a href="stackoverflow.com">lorem</a>) (ipsum)
<ul>
<li>etc.</li>
<li>etc.</li>
<li>etc.</li>
<li>etc.</li>
</ul>
(foobar) (<a href="example.com">barfoo</a>) | (<a href="stackoverflow.com">lorem</a>) (ipsum)
<div>etc.</div>
</div>
CodePudding user response:
Easier than I thought: Remove all childs that are not a
, the rest is trivial.
$('button').click(function() {
var $foo = $('#foo').clone();
$foo.find('*').not('a').remove();
$foo.html($foo.html().trim().replace(/(. )\s*\1/, '$1'));
$('#foo').remove();
$foo.appendTo('#content');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<div id="foo">
<div>etc.</div>
<div>etc.</div>
(foobar) (<a href="example.com">barfoo</a>) | (<a href="stackoverflow.com">lorem</a>) (ipsum)
<ul>
<li>etc.</li>
<li>etc.</li>
<li>etc.</li>
<li>etc.</li>
</ul>
(foobar) (<a href="example.com">barfoo</a>) | (<a href="stackoverflow.com">lorem</a>) (ipsum)
<div>etc.</div>
</div>
</div>
<button>Click me!</button>