简体   繁体   English

如何定位特定节点?

[英]How can I target a specific node?

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).目前它正在检查文本的子注释(node.nodeType === 3)。 The problem is, sometimes there are fe links or the text is strong in the paragraph and they are getting removed too.问题是,有时有 fe 链接或段落中的文本很强大,它们也被删除了。

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)或者换句话说是这样的: 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.目前,该脚本将查看两个文本之间的 3 个元素,并从 Text2 中删除强元素,但这不是我想要的。 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);
});
  
}

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.底层的 Range 和 Selection 对象很容易掌握,然后您就不需要任何秘诀就可以让它们做您想做的事。

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.一些有问题的长字符串不是“段落”,因此不能指望它来解决所有溢出问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM