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

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

1 Answers1

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.

CH4B
  • 734
  • 1
  • 9
  • 27
  • 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 .. – user2319726 Jan 20 '20 at 19:20
  • 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 – CH4B Jan 20 '20 at 19:40
  • its angular 6 app. – user2319726 Jan 21 '20 at 04:56
  • Try taking a look here https://stackoverflow.com/questions/38944725/how-to-get-dom-element-in-angular-2/39679241 @user2319726 – CH4B Jan 21 '20 at 13:38