Reputation: 884
I'm working with "clean" javascript (no libs) and I am wondering about how can I perhaps make the following sample code shorter:
const element = document.createElement("div");
element.style.width = "100px";
element.style.height = 100px;
element.style.backgroundColor = "pink";
element.style.border = "1px solid black";
element.borderRadius = "20px";
When there are enough style properties to handle it becomes this annoying block of code. If there was chaining involved (as in jQuery) I could have at east add some indentation that would have made it a little easier on the eyes when going through the code.
So basically i'm asking for a no-dependency javascript suggestion offering either a shorter method to write the above code, or a prettier style to write it in.
Thanks, CodeAt30
Upvotes: 2
Views: 60
Reputation: 1721
You said that it would be nice to have css chaining calls without using jQuery. Actually, it's pretty simple to put a simple function together that can do just this in plain old javascript.
I've created an example for you:
function createElement(type) {
const elem = document.createElement(type);
return {
baseElement: elem,
css: function(key, value) {
this.baseElement.style[key] = value;
return this;
},
toDOM: function() {
return this.baseElement;
}
};
}
which you can then use like this:
function test() {
var elem = createElement("div").css("width", "100px").css("height", "100px").css("backgroundColor", "pink").css("border", "1px solid black").css("borderRadius", "20px").toDOM();
document.body.appendChild(elem);
}
You'd have to include this helper function as a "dependecy" but as you can just paste it into your own javascript, I don't think of it as a real dependency.
Here you can see it in action as well:
function createElement(type) {
const elem = document.createElement(type);
return {
baseElement: elem,
css: function(key, value) {
this.baseElement.style[key] = value;
return this;
},
toDOM: function() {
return this.baseElement;
}
};
}
function test() {
var elem = createElement("div").css("width", "100px").css("height", "100px").css("backgroundColor", "pink").css("border", "1px solid black").css("borderRadius", "20px").toDOM();
document.body.appendChild(elem);
}
<button onclick="test()">Test</button>
Upvotes: 1
Reputation: 68665
If this can be considered as shorter, you can try to use Object#assign to set the properties.
Object.assign(element.style, {
width: '100px',
height: '100px',
backgroundColor: 'pink',
border:"1px solid black"
});
Upvotes: 1