简体   繁体   中英

changing class name without changing style in javascript

I can't disable events on some element (even by element.onclick = null) so I decided to change name of element.
I tried just by:

element.className = "newOne";

But it made my element dissapear, most probably because it cleared styles.
My second approach included saving styles and then re-copying it to old element:

TempStyles = element.styles.cssText;
element.className = "newOne";
element.styles.cssText = tempStyles;

I tried both with .cssText and without it, non of them works.

If you previously attributed a class to that HTML element, doing element.className = "newOne" will replace all your other classes with newOne , as well as any styles associated with them.

If you want to maintain you old classes and respective styles, you must append the new class to your HTML element:

element.className += " newOne";

Note that extra space before the new class name. It is needed to separate the new class name from the previous, so the property will hold oldClass newOne and not oldClassnewOne . That way, your element has now two classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM