user1719826
user1719826

Reputation:

Apply CSS using Javascript

How can I apply elements like the following CSS in JavaScript:

.watch-non-stage-mode .player-width {
    width : 640px !important;
}

I tried doing this but it's not working:

document.getElementByClassName('.watch-non-stage-mode .player-width').style.width = '640px !important';

Upvotes: 0

Views: 69

Answers (2)

Rob
Rob

Reputation: 15168

The unit, 'px', and '!important' must be added to the property separately. Do:

document.querySelector('.watch-non-stage-mode .player-width').style.width = 640 + 'px' + '!important';

Also, use querySelector as noted to select the elements by the actual dot classname. You cannot use '.classname' in the manner you show (which is incorrect anyway). Elements is plural. getElementsByClassName

Upvotes: 0

marsh
marsh

Reputation: 1441

Try to use querySelector:

document.querySelector('.watch-non-stage-mode .player-width').style.width = '640px'

or if !important is necessarily:

document.querySelector('.watch-non-stage-mode .player-width').style.cssText = 'width: 640px !important;'

In your case you also may use getElementsByClassName, but you incorrectly got a node, must be:

document.getElementsByClassName('watch-non-stage-mode player-width')[0]

Upvotes: 4

Related Questions