0

I am trying to expand toggle class using JavaScript but its not working, i am using setAttribute('aria-expanded', 'true') its giving error set-attribute is null.

(document.getElementById("collapseid")as HTMLTextAreaElement).setAttribute('aria-expanded', 'true')

How can we expand the toggle area with div id using JavaScript and without use of click. i am not sure set attribute will solve the issue, i tried to set the attribute true using Edit Html option but it dint work. unless i click on the toggle button its not expanding, please let me know how to achieve this

2
  • I don't see your html element but did you try document.getElementById("collapseid").setAttribute('aria-expanded', 'true') ? Commented Jan 20, 2020 at 18:59
  • @chg, yes i tried but its giving set attribute null error .. Note:HTML is too long to paste it here Commented Jan 20, 2020 at 19:08

1 Answer 1

0

Document.getElementById will already return you an Element object, no need for that 'as ...' that you're doing.

The function .setAttribute is supposed to work in any Element object, so you can fix it by simply doing:

let collapseObject = document.getElementById("collapseid")
collapseObject.setAttribute('aria-expanded', 'true')

Now, if you need to add or remove a class, I recommend using the classList.add() and classList.remove() functions.

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

4 Comments

Thanks for the reply.. angular application is not accessing element without use of as html .. i tried to set attribute but its throwing set attribute is null error ..
Let' see. Is it an AngularJS app, or Angular 2+ app? You see, using the document.getElement... is a bad practice when using Angular, there are better ways
its angular 6 app.
Try taking a look here stackoverflow.com/questions/38944725/… @user2319726

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.