view raw
iKonenn iKonenn - 6 months ago 46
HTML Question

jquery remove nodes and keep children

I am very ashamed to post this question but I have not managed to get use of unwrap or replaceWith methods in Jquery for that need.

My problem is simple : I need to remove some nodes (jquery selectors) of an html code without losing the children of these nodes.

Here is a Jsfiddle that demonstrate the result of my unsightly code used to reach my goal (yes it's works...)

// var content : the html source code of the wysiwyg

var result = '';
var addContent = '';
// textNode
if(this.nodeType == 3) {
// Text Node
result+= $(this).text();
} else if(this.nodeType == 1 && $(this).hasClass('atwho-inserted')) {
// if is an Object Node with the target class
// I only keep it's contents (means that ".atwho-inserted" is not kept)
result+= $(this).html();
} else {
// in any other case I keep it entirely
result+= this.outerHTML;

Could you find me a really better code (with unwrap method) ?

Thank you a lot :)


I think this one would please you. Notice modification of var tmp

  var content = $('.start').html();
  $('.startCode code').text(content);
  var tmp = $(content);
  $('.atwho-inserted', tmp).children().unwrap();
  var result = tmp.html();
pre code, .wrap{
  white-space: pre-line;
<script src=""></script>

<div class="container">
  <div class="row">
    <div class="col-xs-6">
      <div class="well">All selectors ".atwho-inserted" are in "background-color:red" and have to be removed without losing its children.</div>
      <div class="start">
          <span class="atwho-inserted" data-atwho-at-query="@fac" contenteditable="false">
            <span class="user_mention" data-identifier="8930">@facticeuserr</span>
          <br /> some lorem ipsum text
          <span class="atwho-inserted" data-atwho-at-query="#acc" contenteditable="false">
            <span class="tag_mention" data-identifier="484">#accessibilité</span>
          <img src="" data-filename="3">
          <br />
          <span class="atwho-inserted" data-atwho-at-query="#acc" contenteditable="false">
            <span class="tag_mention" data-identifier="653">#Accompagnement</span>
      <pre class="startCode"><code></code></pre>
    <div class="col-xs-6">    
      <div class="well">Here the result<br /> it's works but code is not optimized</div>
      <div class="result"></div>
      <pre class="resultCode"><code></code></pre>