HTMLCollection shows length 0 when elements exist in parent

507 views Asked by At

I am using apple's MapKit JS to embed a map into a webpage. I need to get access to marker annotations in the underlying HTML Shadow Dom, i want to add a classname to the elements. Using the browser developer tools I can "see" the shadow dom

Shadow Dom Structure

I use the following code to "traverse" the shadow 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)

When this is run, the console logs shows the mapAnnotations does have a childElementCount of 2 and the nodes are shown in the childNodes and children attributes. However, when reading the children or childnodes it is displaying that there are no children and the resulting HTMLCollection in variable annotationMarkers has two elements but a length of 0.

Console Output showing parent node with children

Console Output shwoing logging messages

I have seen several similar questions where the answer seems to be that the DOM is not completely loaded, although when logging the parent node this does show child elements.

So my question is in 2 parts, does the parent element know it has 2 children but these elements arent actually loaded at that point and

secondly, is there a way to perform a similar $(document).ready function call on the shadowDom? Thus ensuring that all elements in the shadowDom (or all child elements of the parent mapAnnotations node) has been loaded?

I have tried a ready function on the shadowRoot element and had an eventListener attached listening for DomContentLeaded event but this doesnt fire at all.

Update 30/09/2020 @ 20:30

I have put a setTimeout in the JS, and the child node count is now showing as 2 after the timeout completes. I need to find a way to wait on the completion of the shadowDom and for elements to exist :/

1

There are 1 answers

2
ilyas Jumadurdyew On

With Jquery library

var child_items = $('.your_parrent_class').find('li');

console.log(child_items.length);