Итак, я возился с JS, пытаясь создать метод, который добавляет стиль CSS к элементам без удаления применяемого в данный момент стиля:
// ==================================================================================================
// this method adds style to an element using CSS inline syntax without removing unaltered CSS styles
// ==================================================================================================
Element.prototype.cssStyle = function (style)
{
let styleChars = style.split(''); // split each character of the style arg as an item in an array
let positions = [];
for(let i=0; i<styleChars.length; i++){
if(styleChars[i] === '-'){
positions.push(i+1);
};
};
positions.forEach(function (position){ // for each match
styleChars.splice(position, 1, style[position].toUpperCase()); // make that character uppercase
});
styleChars.splice(0, 0, '[["'); // add a "[[" item on the first position
styleChars.splice(styleChars.length, 0, '"]]'); //add a "[[" on the last position
style = styleChars.join('') // join back the array into a string
style = style.replace(/:/g, "\",\"").replace(/;/g, "\"],[\"").replace(/-/g, ""); // replace some character in order to make the string look like an array
style = JSON.parse(style); // parse the string into an array
for(let i=0; i<style.length; i++){ // for each item in the array
let property = style[i][0].replace(/ */, ""); // remove some characters which might inhibit normal execution
let value = style[i][1].replace(/;/, "").replace(/ */, ""); //remove some characters which might inhibit normal execution
this.style[property] = value // change style of the element
};
return this.getAttribute('style'); //return all inline CSS styles
}
, поэтому, если я попытаюсь стилизовать такой элемент, как это:
Element.cssStyle('background-color: white; color: #000')
Он работает, как ожидалось, но если я добавлю ;
в конец строки параметра, я получу это
Element.cssStyle('background-color: white; color: #000;')
'Uncaught TypeError: Cannot read property 'toUpperCase' of undefined'
Хотя я не Не вижу никаких явных проблем с методом замены, что это может быть?
Замена пробелов в этой строке работает нормально, но при попытке заменить ;
я получаю эту ошибку.
Также насколько плохо написан мой код?
Спасибо!