How can I target a specific node?

Viewed 29

My setup is below.

It is working, I just have a small issue with it. Currently its checking for child notes that are text (node.nodeType === 3). The problem is, sometimes there are f.e. links or the text is strong in the paragraph and they are getting removed too.

Basically what I want to do is: target (count) everything in a paragraph that is NOT a break. Or in other words something like this: if(node.nodeType !== br)

An Example would look something like this:

<p>
  "Text"
  <br>
  <br>
  <strong>
  "Text2"

Currently the script would look at the 3 elements between the two texts and would remove the strong element from Text2 but that is not something I want. It should only count the paragraphs and nothing else.

Can somebody help me out please?

const mediaQuery = window.matchMedia('(max-width: 468px)')
// Check if the media query is true
if (mediaQuery.matches) {
  const paragraphs = document.querySelectorAll("p");

paragraphs.forEach( elem => {
  const nodes = [...elem.childNodes];
  nodes.reduce((count, node) => {
    if(node.nodeType === 3) {
      const isEmpty = node.nodeValue.trim().length === 0;
      return isEmpty ? count : 0; 
    }
    count++;
    if (count>2) node.remove();
    return count;
  }, 0);
});
  
}
1 Answers

You can find some recipes for common tasks at the end of the chapter, in “ paragraphs” section. Maybe that covers your current needs, but you’ll get much more if you read the whole text.

The underlying Range and Selection objects are easy to grasp, and then you’ll need no recipes to make them do what you want.

If a ‘ paragraphs’ straddles the end of the line, we can hyphenate it.

I guess “ paragraphs” helps put a finger on the issue there. Some problematically long strings aren’t “ paragraphs” so it can’t be counted on to solve all overflow issues.

Related