My javascript code looks like this:
const xx = e.target.parentElement.children[1].children[1].innerHTML;
imgText.innerHTML = xx;
It gets the innerHTML
of a paragraphs of all cards within a div, and then insterting that into another paragraph somewhere else.
The thing is, that not every card has the last children[1]
and it throws an error in the console:
Uncaught TypeError: e.target.parentElement.children[1].children[1] is undefined
Can I make it so it first checkes if the xx
exists and then it would go to the second line of code?
I have tried using
if (x != null){}
else{}
But it would throw the same error, any suggestions?
CodePudding user response:
You can use Element.childElementCount
to check if the element has the child and, if true, retreive it.
const x = e.target.parentElement.children[1]
if(x.childElementCount > 0) {
const xx = x.children[1].innerHTML
// Use xx
}
Please use appropriate variable names.
CodePudding user response:
You can use optional chaining to make the whole expression return null if one element is null.
const xx = e.target?.parentElement?.children?.[1]?.children?.[1]?.innerHTML;
if (xx != null) {
...