I am sure this must of been asked before but can't find any in the search. What is the fastest way to ensure all non safe characters are removed from a string allowing it to be used in a CSS class name?
The document. getElementById() method is used to return the element in the document with the “id” attribute and the “className” attribute can be used to change/append the class of the element.
To join together strings in JavaScript you can use a different type of string, called a template literal. You can use the same technique to join together two variables: const one = "Hello, "; const two = "how are you?"; const joined = `${one}${two}`; console. log(joined); // "Hello, how are you?"
To change all classes for an element:getElementById("MyElement"). className = "MyClass"; (You can use a space-delimited list to apply multiple classes.)
Converting Values to Strings Values can be explicitly converted to strings by calling either String() or n. toString() . With the String() function, let's convert a Boolean value to a string by passing the value true into the parameters for String() .
I would replace anything that is not a lowercase letter or digit, and then I would add a special prefix to avoid collisions with class names you have used for other purposes. For example, here is one possible way:
function makeSafeForCSS(name) { return name.replace(/[^a-z0-9]/g, function(s) { var c = s.charCodeAt(0); if (c == 32) return '-'; if (c >= 65 && c <= 90) return '_' + s.toLowerCase(); return '__' + ('000' + c.toString(16)).slice(-4); }); } // shows "prefix_c_a_p_s-numb3rs-__0024ymbols" alert("prefix" + makeSafeForCSS("CAPS numb3rs $ymbols"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With