Reputation: 5
I have a DOM object e.g. div with any children. I need to subdivide it correctly into two parts: before marked element and after. Example:
<div>
<p>para 1</p>
<a href="#">Some text here
<b>Bold<em>Italic <span id="marker"></span> </em> any other text</b>
<p>Cool para 2</p>
</a>
<span>Bla-bla</span>
</div>
The result should be like that:
<div>
<p>para 1</p>
<a href="#">Some text here
<b>Bold<em>Italic</em></b>
</a>
</div>
<span id="marker"></span>
<div>
<a href="#">
<b><em>text</em> any other text</b>
<p>Cool para 2</p>
</a>
<span>Bla-bla</span>
</div>
As you can see all tags are closed correctly, correct links, etc. The way I see is to clone DOM node, insert the marker between first node and its clone, remove right elements in first node and left elements in clone node. But how to do it I don't know. So I need an example or function in pure JS or JQuery.
Upvotes: 0
Views: 194
Reputation: 18233
Text nodes aren't considered siblings and so are ignored by the jQuery DOM traversal methods. To split the text string, you will have to parse that manually (or simply insert the marker in a more meaningful spot). This demo should be very close to what you want, but the text on the same level as the marker won't be split.
$(document).ready( function() {
var $contentDiv = $('div');
var $prev = $contentDiv.clone();
$prev.find("#marker").parentsUntil('div').andSelf().nextAll().remove();
$prev.find("#marker").parentsUntil('div').andSelf().prevAll();
$prev.find("#marker").remove();
var $next = $contentDiv.clone();
$next.find("#marker").parentsUntil('div').andSelf().prevAll().remove();
$next.find("#marker").parentsUntil('div').andSelf().nextAll();
$next.find("#marker").remove();
$contentDiv.after($next);
$contentDiv.after("<hr />");
$contentDiv.after($prev);
$contentDiv.after("<hr />");
});
Upvotes: 1