Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript InvalidCharacterError when modifying a css name with a space

I'm modifying some buttons that are dynamically generated through JavaScript. I have no control over statically declaring the class names which is why I've written a function to do it for me on page load. I understand why it's happening (it doesn't like the space in 'zocial button'), I just need a fix and I'm definitely not that gifted with JavaScript. Here's the error if you inspect the button on the page: Unncaught InvalidCharacterError: Failed to execute 'add' on 'DOMTokenList': The token provided ('zocial facebook') contains HTML space characters, which are not valid in tokens. Here's my javascript code:

var buttonz = document.getElementsByName('provider');
for (var i = 0, length = buttonz.length; i < length; i++) {
    if (buttonz[i].value == 'Facebook')
    {
        buttonz[i].classList.remove('btn-default');
        buttonz[i].classList.add('zocial button');
    }

If you want to see it live here you go: http://jsbin.com/nifuxoyo/1/watch

like image 965
DigitalRayne Avatar asked Mar 02 '14 21:03

DigitalRayne


1 Answers

Well, class names cannot contain spaces, because the space separates multiple class names from each other. For example, if your HTML contains

class="zocial button"

it means that this element has two classes, "zocial" and "button".

If you want to add both of these classes, you have to pass each one as argument to the method:

buttonz[i].classList.add('zocial', 'button');

More information can be found in the MDN documentation.

like image 138
Felix Kling Avatar answered Nov 18 '22 13:11

Felix Kling