A
A
Alex_872020-11-26 14:20:37
JavaScript
Alex_87, 2020-11-26 14:20:37

How to recursively remove text nodes?

How to recursively remove text nodes?

Example:
After executing the function, the tree

<span> <div> <b>привет</b> </div> <p>loftchool</p> !!!</span>

should be converted to I tried to solve it like this , but I can't figure out why the childNodes property behaves so strangely, I can't figure out what the error is. <span><div><b></b></div><p></p></span>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-11-26
@Alex_87

First - you pass a string to the function and use it as a selector, it's not clear how you intend to do this recursively? Let the function immediately get the element.
Second, you are bypassing childNodes which is a dynamic NodeList and trying to modify it at the same time. By deleting one element, you skip the next one - i.e., if several text elements are in a row, then only every second element will be deleted; and those non-text elements that are located after the text ones, no recursion will happen here, their content will not be processed at all. We need to make a copy of childNodes and iterate over it. Or, instead of for-of, use a loop with a counter; when an element is removed, the counter should not increase.
Thirdly - some kind of nonsense with nextElementSibling, I don't know how to comment on it. You just had to call the function, passing it the current element.

Fourth.
const deleteTextNodes = el =>
  el.nodeType === 3
    ? el.remove()
    : [...el.childNodes].forEach(deleteTextNodes);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question