In Javascript this Code works like a acharm, in Typescript I get the following Error:
Property 'children' does not exist on type 'Node'.
This is my code
var parser = new DOMParser();
var res = parser.parseFromString(xmldata, "text/xml")
var branches = res.getElementsByTagName("Branch")
branches[i].childNodes[7].children
In Javascript this Code works like a acharm, in Typescript I get the following Error:
Property 'children' does not exist on type 'Node'.
This is my code
var parser = new DOMParser();
var res = parser.parseFromString(xmldata, "text/xml")
var branches = res.getElementsByTagName("Branch")
branches[i].childNodes[7].children
Share
Improve this question
edited Jul 31, 2017 at 11:47
ADreNaLiNe-DJ
4,9193 gold badges27 silver badges35 bronze badges
asked Jul 31, 2017 at 11:41
FloFlo
3,0674 gold badges26 silver badges52 bronze badges
1
-
instead of
childNodes
you could trychildren
which should return instances ofElement
instead ofNode
– the8472 Commented Jul 31, 2017 at 12:09
2 Answers
Reset to default 8The error occurs because there is no field children
in the definition file for the Node
interface. The typescript piler will prompt an error if the property you're trying to access on an object does not exist. You can see the entire definition file here.
What happens is that the selected child node is an instanceof Element
. The childNodes
method returns an implementation of the interface NodeList
which is an iterator for objects of the type Node. When you look at the definition for the Element interface, you can see that it inherits Node
, ChildNode
and ParentNode
interfaces. The ParentNode interface is the one that contains the readonly attribute children
. You can apply casts to objects in Typescript to the proper element type.
let el = <Element> branches[i].childNodes[7];
el.children;
// or without declaring a new variable
(<Element> branches[0].childNodes[0]).children;
This should work with typescript
const parentEl = document.getElementById('parentId')
if (!parentEl) {
return
}
const childElements = Object.values(parentEl.childNodes) as HTMLElement[]
for (const childEl of childElements) {
console.log(childEl.offsetLeft)
}