首页 > 解决方案 > 使用文档选择器选择自定义元素

问题描述

我正在用 Stenciljs 编写一个应用程序,我的自定义元素如下:

<custom-alert alertType="warning" alertId="warningMessage" hide>Be warned</custom-alert>

现在,问题在于通过document.querySelector()或任何其他方式选择此元素以删除或添加hide属性。这可以很容易地为标准 HTML 元素完成:

document.querySelector('input').removeAttribute('hide');

如何为我的自定义元素执行此操作?

标签: javascripttypescriptstenciljs

解决方案


通过添加 id 属性,我能够获得所需的结果

<custom-alert id="myCustomAlert" alertType="warning" alertId="warningMessage" >Be warned</custom-alert>

然后可以隐藏该组件并显示如下:

document.getElementById('myCustomAlert').setAttribute('hidden', 'true');

并显示如下:

document.getElementById('myCustomAlert').removeAttribute('hidden');

推荐阅读