Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Get child of DOM element

I want to get all children elements of a particular element in .gui file and modify their attributes 

Basically, I have 

 

<g id="parent-0">
      <text id="parent-0-text-0"/>
     <text id="parent-0-text-1"/>
    <text id="parent-0-text-2"/>
</g>
.
.
.
<g id="parent-100">
<text id="parent-100-text-0"/>
<text id="parent-100-text-1"/>
<text id="parent-100-text-2"/>
</g>

Now I want to get "parent-0" and for each text in it, I want to set text value.

I want to avoid directly getting document.getElementById("parent-0-text-1") as there Are hundreds of such parents and Each clock tick; I want to modify only one of the parents

 

Can I do something like

document.getElementById("parent-99).childNodes[0].text = "foo-1"
document.getElementById("parent-99).childNodes[1].text = "foo-2"
document.getElementById("parent-99).childNodes[2].text = "foo-3" 
Best Answer
0 Votes
6 REPLIES 6

You can use getElementsByClassName, or getElementsByTagName.

 

<g id="parent-0">
  <text class="someText" />
  <text class="someText" />
  <text class="someText" />
</g>

let parent0 = document.getElementById("parent-0");
let childTexts = parent0.getElementsByClassName("someText");
childTexts[0].text = "something";
// etc

or

<g id="parent-0">
<text />
<text />
<text />
</g> let parent0 = document.getElementById("parent-0"); let childTexts = parent0.getElementsByTagName("text"); childTexts[0].text = "something"; // etc
Best Answer

That kind of worsen the problem.

Now my clock takes even longer to render.

May be I need to find some other solution

Best Answer
0 Votes

Can you describe what you're trying to achieve and show some more code?

Best Answer
0 Votes

Got it working.

Your solution greatly helped.

I selected elements by Tag, but needed to make many changes to my code to make rendering faster.

 

Thanks Jon !

Best Answer
0 Votes
document.getElementById("foo").children

would be very useful and more performant than searching for all elements by className. Please add this to the SDK.

Best Answer
0 Votes

We have firstChild/nextSibling, so you could achieve the same thing without using classes/IDs:

 

let elem = parent.firstChild;
while (elem) {
  // do something with elem
  elem = elem.nextSibling;
}

Could possibly write a children polyfill to get the same ergonomics you suggest too.

Best Answer
0 Votes