我正在使用Apple的MapKit JS将地图嵌入到网页中。我需要访问底层HTML Shadow Dom中的标记注释,我想为元素添加一个类名。使用浏览器开发人员工具,我可以“看到”影子dom
我使用以下代码“遍历”阴影dom:
let annotationContainer = document.querySelector(".mk-annotation-container");
let mapAnnotations = annotationContainer.shadowRoot.querySelector(".mk-annotations");
console.log(mapAnnotations);
if (!mapAnnotations.hasChildNodes()) {
console.log("There are NO child nodes");
}
let firstAnnotation = mapAnnotations.firstElementChild;
console.log("First Child: "+firstAnnotation);
var annotationMarkers = mapAnnotations.children;
console.log(annotationMarkers)
运行此命令时,控制台日志显示 mapAnnotations 的childElementCount确实为2,并且节点显示在childNodes和children属性中。但是,在读取子节点或子节点时,它表明没有子节点,并且变量 annotationMarkers 中生成的HTMLCollection具有两个元素,但长度为0。
Console Output showing parent node with children
Console Output shwoing logging messages
我看到了几个类似的问题,答案似乎是DOM没有完全加载,尽管在登录父节点时确实显示了子元素。
所以我的问题分为两部分,父元素是否知道它有2个子元素,但实际上这些元素在那时并没有加载
第二,有没有一种方法可以在shadowDom上执行类似的$(document).ready函数调用?从而确保shadowDom中的所有元素(或父mapAnnotations节点的所有子元素)已加载?
我已经尝试了shadowRoot元素上的ready函数,并附加了一个eventListener来监听DomContentLeaded事件,但这根本不会触发。
更新30/09/2020 @ 20:30
我在JS中放置了setTimeout,并且超时完成后,子节点计数现在显示为2。我需要找到一种方法来等待shadowDom完成并等待元素存在:/
答案 0 :(得分:-1)
使用Jquery库
var child_items = $('.your_parrent_class').find('li');
console.log(child_items.length);