从DOM片段中删除具有特定颜色的<font>

时间:2018-05-02 08:09:36

标签: javascript html

这是DOM片段

enter image description here

我正在使用:

var range = window.getSelection().getRangeAt(0);
var selectionContents = range.cloneContents();
console.log(selectionContents) // <-- it displays DOM fragment from selection.

我想删除<font color="#0000ff">&nbsp;Smith</font>

enter image description here

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

如果要删除具有<font>特定color属性的#0000ff元素,则只需在selectionContents节点内迭代搜索该元素,然后删除符合您条件的节点:

var fontEls = selectionContents.querySelectorAll('font');
fontEls.forEach(function(fontEl) {
  if (fontEl.color === '#0000ff')
    fontEl.remove();
});

请参阅下面的概念验证(并检查您的控制台):

&#13;
&#13;
document.querySelector('button').addEventListener('click', function() {
  var range = window.getSelection().getRangeAt(0);
  var selectionContents = range.cloneContents();
  
  var fontEls = selectionContents.querySelectorAll('font');
  fontEls.forEach(function(fontEl) {
    if (fontEl.color === '#0000ff')
      fontEl.remove();
  });
  
  console.log(selectionContents);
});
&#13;
<div>
  There, <b>Samuel<font color="#0000ff">&nbsp;Smith</font><font color="#ff0000">&nbsp;Smith</font><font color="#00ff00">&nbsp;Smith</font></b>
</div>
<button type="button">Get selection</button>
&#13;
&#13;
&#13;