1

When i execute a JS code in typescript, i get the following error:

ORIGINAL EXCEPTION: TypeError: Cannot read property 'setAttribute' of null

But It works perfectly in JS without any errors.

<HTML>
<path id="border" transform="translate(125, 125)"  style="stroke:white; marker-end:url(#InverseSemicircleEnd);"/>
</HTML>

TS:
document.getElementById("border").setAttribute("style",dec);

But not sure, why it results in error on TS. I also tried to change the name of the property for this ID, but no luck. Can some one help me in explaining on what i'm doing wrong here.

Thanks For your support Regards Suresh

3
  • Where is the TS code? Please post the whole component to see how the stuff is related. Commented Sep 1, 2016 at 11:16
  • 5
    Looks like you are calling it before the HTML is rendered Commented Sep 1, 2016 at 11:16
  • @JuanMendes: Yes that's what happening. Thanks for pointing that out.. Commented Sep 2, 2016 at 6:08

2 Answers 2

1

Because document.getElementById could return null, you need to check if it is different from null.

const myEl = document.getElementById("border");
if (myEl !== null) {
  myEl.setAttribute("style",dec);
}

OR

document.getElementById("border")?.setAttribute("style",dec);

If you are sure that the element is defined and you want to avoid the check, use the ! (Non-null assertion) operator:

document.getElementById("border")!.setAttribute("style",dec);

Make sure that the browser has loaded before querying elements because not doing so could lead to a runtime error.

Sign up to request clarification or add additional context in comments.

Comments

0

I use the following way to solve :

  hideDesPan(){
    let pan = (<HTMLInputElement>document.getElementById('showPan'));
    pan.style.display = "none";
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.