Vanilla Javascript中的contents()。filter()的等价物

问题描述 投票:0回答:3

我有一些我需要在Vanilla JS中重写的JQuery代码。

$('#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
3个回答
0
投票

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

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

0
投票

这是一个vanilla JavaScript解决方案。您可以检查代码背后的逻辑注释:

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">

0
投票

我想我已经明白了;

这是我的解决方案;

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的意见。它使我朝着正确的方向前进。

© www.soinside.com 2019 - 2024. All rights reserved.