Answer the question
In order to leave comments, you need to log in
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>
<span><div><b></b></div><p></p></span>
Answer the question
In order to leave comments, you need to log in
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.
const deleteTextNodes = el =>
el.nodeType === 3
? el.remove()
: [...el.childNodes].forEach(deleteTextNodes);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question