检查元素是否包含#shadow-root [英] Check if element contains #shadow-root

查看:67
本文介绍了检查元素是否包含#shadow-root的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以查看Shadow DOM元素是否存在?我不太关心操纵它,甚至不是说真的针对它.我了解封装的原因.但是我希望能够根据是否存在Shadow DOM元素来设置常规DOM中的其他元素的样式.

Is it possible to see if a Shadow DOM element exists? I'm not too concerned with manipulating it, or even really targeting it per-say. I understand the reasoning of the encapsulation. But I'd like to be able to style other elements in the regular DOM, based on whether or not the Shadow DOM element is present.

喜欢的排序:

if ( $('#element-id #shadow-root').length ) {
    // true
}

或者,如果不是阴影根,则至少包含其中的特定元素,例如div的ID.因此,如果该div存在,那么显然该Shadow DOM元素在页面上.

Or if not for the shadow-root, at least a specific element within, like the id of a div. So if that div exists, then clearly that Shadow DOM element is on the page.

我知道这不是那么简单...从我所做的一些研究中,可以发现>>> /deep/,但他们的支持似乎很少/没有/弃用.购买也许还有另一种方式,但是可能不够优雅?

I know it wouldn't be that simple... From some research I've done, there are things like >>> and /deep/ but their support seems to be low/none/deprecated. Buy maybe there's another way, however inelegant it may be?

推荐答案

如果您要检查特定元素是否托管了 open 影子DOM元素,您可以执行以下操作:

If you want to check whether or not a specific element is hosting an open Shadow DOM element, you can do the following:

var el = document.querySelector('#some-element');
if (!!el.shadowRoot) {
    // Then it is hosting an OPEN Shadow DOM element
}

您还可以获取Shadow DOM元素,然后像普通节点一样对其进行操作:

You can also get the Shadow DOM element, and then operate on it like a normal node:

var shadowEl = el.shadowRoot;
// And for example:
console.log(shadowEl.innerHTML);

以下是在最新版本的Chrome中运行的示例:

Here is an example that works in the latest version of Chrome:

const div = document.querySelector('div');
const p = document.querySelector('p');

const shadowRoot = p.attachShadow({mode: 'open'})
shadowRoot.textContent = 'A Shadow DOM Paragraph. I overrode the content specified!';

console.log('Paragraph has Shadow DOM:', !!p.shadowRoot); // true
console.log('Div has Shadow DOM:', !!div.shadowRoot); // false

<div>A Normal Div</div>
<p>A Normal Paragraph</p>

这篇关于检查元素是否包含#shadow-root的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆