从父级而不是子级删除标签

时间:2019-06-11 03:10:08

标签: javascript jquery regex dom-manipulation

我想从<br>删除&nbsp;标签和<div>标签,但不从子span类代码中删除

这是我的dom外观

<div>
 some &nbsp; text
 <br>
 some &nbsp;text
 <br>
 some &nbsp; text

 <span class='code'>//Code
  <pre>
   <p>
    &nbsp;text here 
    <br>
    &nbsp;text here 
    <br>
    &nbsp;text here 
    <br>
   </p>
  </pre>
 </span>

</div>

这是jquery还是javascript

2 个答案:

答案 0 :(得分:1)

您可以这样:

var divhtml = $('.code').parent().html().replace(/<br>/g,'').replace(/&nbsp;/g,'');
$('.code').parent().html(divhtml);

答案 1 :(得分:0)

// Get the code span
var codeSpan = document.querySelector("span.code");

// Remove the codeSpan from the DOM
codeSpan.remove();

// Get the div
var div = document.querySelector("div");
var html = div.innerHTML;

// Remove all the <br> and &nbsp; from the div
div.innerHTML = html.replace(/<br>/g,'').replace(/&nbsp;/g,'');

// ---- Alternate approach
// Clear out all the content from the div
// div.innerHTML = "";

// Add the codeSpan back into the div
div.appendChild(codeSpan);
<div>
 some &nbsp; text
 <br>
 some &nbsp;text
 <br>
 some &nbsp; text

 <span class='code'>//Code
  <pre>
   <p>
    &nbsp;text here 
    <br>
    &nbsp;text here 
    <br>
    &nbsp;text here 
    <br>
   </p>
  </pre>
 </span>

</div>