Эквивалент содержимого (). Filter () в ванильном JavaScript - PullRequest
0 голосов
/ 20 марта 2019

У меня есть этот бит кода 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 ().

Был бы очень признателен за помощь в этом. Спасибо.

Ответы [ 3 ]

0 голосов
/ 20 марта 2019

Вот ванильное решение 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 голосов
/ 21 марта 2019

Мне кажется, я понял это;

Это было мое решение;

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 за ваш вклад. Это привело меня в правильном направлении.

0 голосов
/ 20 марта 2019

Вы можете преобразовать его в массив с помощью Array.from, а затем использовать функцию filter массива:

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