【问题标题】:Equivalent of contents().filter() in Vanilla Javascript等价于原版 Javascript 中的 contents().filter()
【发布时间】:2019-03-20 16:34:59
【问题描述】:

我有这段 JQuery 代码需要用 Vanilla JS 重写。

$('#myID :not(a, span)').contents().filter(
function() {
      return this.nodeType === 3 && this.data.trim().length > 0;})
.wrap('<span class="mySpanClass" />');

我试过了;

Array.prototype.forEach.call(document.querySelectorAll('#myID  :not(a), #myID :not(span)'), 
function(el, i){
    var span = document.createElement('span');
    span.setAttribute('class', 'rvReaderContent');
    while((el.firstChild) && (el.firstChild.nodeType === 3) && (el.firstChild.data.trim().length > 0)){
       var textNode = el.firstChild
      el.insertBefore(span, textNode);
      span.appendChild(textNode);   
    }
});

我尝试了其他变体,但似乎没有任何效果。我找不到 JQuery 的 contents() 方法的替代品。

非常感谢您对此的帮助。谢谢。

【问题讨论】:

标签: javascript jquery equivalent


【解决方案1】:

你可以用Array.from将其转换成数组,然后使用Array的filter函数:

Array.from(document.querySelectorAll('#myID  :not(a), #myID :not(span)'))
    .filter(function(el) { ... })
    .forEach(function(el) { ... });

【讨论】:

  • 感谢您的意见。通过修改您的建议,我能够弄清楚。
  • 酷,我很乐意提供帮助。你可以接受答案。
【解决方案2】:

这是一个普通的 JavaScript 解决方案。您可以检查 cmets 以了解代码背后的逻辑:

document.querySelector('#formatBtn').addEventListener('click', format);

function format() {
  //Apply your query selector to get the elements
  var nodeList = document.querySelectorAll('#myID :not(a):not(span)');

  //Turn NodeList to Array and filter it
  var html = Array.from(nodeList)
    .filter(el => el.textContent.trim().length > 0)
    .reduce((accum, el) => {
      //Wrap the textContent in your tag
      accum += `<span class="mySpanClass">${el.textContent}</span>`;
      return accum;
    }, '');
  //Update the HTML
  document.getElementById('formattedHtml').innerHTML = html;
  //Remove other stuff
  document.querySelector('#myID').remove();
  document.querySelector('#formatBtn').remove();
}
.mySpanClass {
  color: red;
}
<div id="myID">
  <a href="#">Some link</a>
  <p id="p1">Paragraph 1</p>
  <p id="p2">Paragraph 2</p>
  <span id="s1">Span 1</span>
</div>

<div id="formattedHtml"></div>

<input id="formatBtn" type="button" value="Format HTML">

【讨论】:

  • 感谢您的帮助。它对我眼前的问题没有多大帮助,但它让我抬头并欣赏 Array.prototype.filter 方法。我还从上面的 sn-p 中学习了如何修复我的选择器。
【解决方案3】:

我想我已经弄明白了;

这是我的解决方案;

Array.from(document.querySelectorAll('#myID :not(a):not(span)'), function(el){
    Array.from(el.childNodes, function(ch){
        if(ch.nodeType === 3 && ch.data.trim().length > 0){
           var span = document.createElement('span');
           span.setAttribute('class', 'mySpanClass');
           el.insertBefore(span, ch);
           span.appendChild(ch);
       }
   });
 });

感谢@ttulka 您的意见。它把我引向了正确的方向。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-20
    • 2017-09-02
    • 1970-01-01
    • 2021-03-29
    • 2023-04-11
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多