javascript - 仅当元素不是另一个元素的子元素时才选择该元素

标签 javascript html dom css-selectors

我目前正在开发一个 Web 组件中继器,当我尝试在同一元素中混合两个中继器时遇到问题。我的 HTML 是:

<company-repeat id="table">
    <table class="selectable" description="Résultats de recherche">
        <thead>
            <tr>
                <company-repeat id="table-metadata">
                    <th class="sorting" repeatable>${name}</th>
                </company-repeat>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <tr repeatable>
                <td>${id}</td>
                <td>${name}</td>
                <td>${surname}</td>
                <td>${registered}</td>
                <td><i aria-hidden="true" class="fa fa-download" title="Télécharger">D</i></td>
            </tr>
        </tbody>
    </table>
</company-repeat>

我想做的是根据我收到的列表动态生成 thead,但问题是我的代码采用它找到的第一个“可重复”元素( this.template = this.querySelector('[repeatable]'); )。我现在需要的是一个选择器来指定我想要它找到的第一个元素,前提是它不是另一个公司重复的子元素。

是否只能使用选择器来实现,还是必须检索所有元素,检查该元素是否是另一个元素的子元素,然后仅将其设置为我的属性?

类似于 document.querySelector('!company-repeat > [repeatable]');会很完美,但我非常怀疑它的存在。

最佳答案

Is it doable only with a selector...

遗憾的是没有,没有。不存在“仅当 X 不是 Y 的后代时才选择 X”的情况。 (人们对 :not 伪类很感兴趣,但它只允许简单的选择器,而不是我们需要的复合类型。)

...or do I have to retrieve them all, check if the element is child of another element and then only set it to my property?

是的,这就是您需要使用的方法。

关于javascript - 仅当元素不是另一个元素的子元素时才选择该元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43185979/

相关文章:

javascript - injectedJavaScript 在 react native 的 Webview 中不起作用

javascript - 页面加载后运行功能但不刷新

javascript - JQuery 灯箱内可拖动图像

javascript - JavaScript 可以访问它自己的源 URL 吗?

c++ - 什么 C/C++ 库用于 HTML DOM 构建/更改?

javascript - localStorage 不会在两个页面之间持久存储

javascript - Opera 从 selectNodeContents 中抛出 DOMException

javascript - 如何在 Firefox WebExtensions 中获取 openerTabId?

javascript - 在 SilverStripe 2.4.7 中使用 Javascript

javascript - 函数中的服务器变量