3

I want to create a prototype function for adding style to element. Similar to the following code:

element.css3("property" , "value");

please help me to write prototype function. this is my code : (has problems)

Object.prototype.css3 = function (property , value) {
  this.style.property = value;
};

1
  • You shouldn't modify builtins, but if you absolutely have to, at least do it properly please. Commented Jan 26, 2017 at 6:45

2 Answers 2

2

Use bracket notation to set a property using a string variable otherwise which sets a property named property. Where use String#replace method to capitalize character after - symbol, to make valid property in Javascript style.

Element.prototype.css3 = function (property , value) {
  this.style[property.replace(/-([a-z])/gi,function(_,m){ return m.toUpperCase(); })] = value;
  // or this.style[property] = value;
};
Sign up to request clarification or add additional context in comments.

13 Comments

@hamidreza : because dot notation sets a property named as property not the string value passed .... for set using a string , use bracket notation
can you write a code for delete ' - ' characters and capital next character?for exam: background-color => backgroundColor
I knew nothing of this Code . /-([a-z])/gi,function(_,m){ return m.toUpperCase(); }
@xxSithRagexx : it's regex
|
0

One way to achieve what you are trying to do is to write it like this:

Object.prototype.css3 = function (property , value) {
  this.style[property] = value;
};

The way it is written now it will be looking for the [property] named property of [style], which does not exist. With this you will be able to pass a string form of the property to the style and change your value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.