Hi. Sometimes, we create code snippets to help us. In a project, I needed to create an element and its attributes should have been set. I wasn't using jQuery or like libraries. I've created a JavaScript function like that.
const element = (data) => {
const el = document.createElement(data["tag"])
if(data["type"]) {
el["type"] = data["type"]
}
if(data["id"]) {
el["id"] = data["id"]
}
if(data["class"]) {
const classList = data["class"]
classList.map(m => {
el.classList.add(m)
})
}
if(data["text"]) {
el["textContent"] = data["text"]
}
if(data["html"]) {
el["innerHTML"] = data["html"]
}
if(data["attr"]) {
const attr = data["attr"]
const keys = Object.keys(data["attr"])
keys.map(m => {
el.setAttribute(m, attr[m])
})
}
if(data["event"]) {
const attr = data["event"]
const keys = Object.keys(data["event"])
keys.map(m => {
const eventName = "on" + m
el.setAttribute(eventName, attr[m])
})
}
if(data["addTo"]) {
const target = document.querySelectorAll(data["addTo"])
target.forEach((m, i) => {
m.appendChild(el)
})
}
if(data["style"]) {
const attr = data["style"]
const keys = Object.keys(data["style"])
let styleCode = '';
keys.map(m => {
const props = attr[m]
const prop_keys = Object.keys(attr[m])
styleCode += `${m} {`
prop_keys.map(p => {
styleCode += `${p}:${props[p]};`
})
styleCode += '}'
})
const style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = styleCode;
document.getElementsByTagName('head')[0].appendChild(style);
}
return el
}
This function always works for me. If you want to use this function you can use like this;
// Example Usage
element({
'tag': 'button',
'type': 'button',
'addTo': '.test-body',
'html': '<img src="https://cdn-images-1.medium.com/max/2000/0*uORWkYMjiF3LA-K8" />', // or text
'id': 'user-card',
'class': ['profile-link', 'avatar'],
'attr': {
'name': 'user-name',
'value': 'Ali',
'data-id': 1,
'data-path': '/profile/1'
},
'event': {
"click": `console.log(123)`
},
'style': {
'.profile-link': {
"color": "#fff",
"background-color": "#000"
},
".profile-link:hover": {
"color": "#000",
"background-color": "#fff",
"border": "1px dashed #000;"
},
".avatar": {
"width": "300px",
"height": "300px",
"border": "1px dashed #e3e3e3;"
},
".avatar img": {
"width": "285px",
"height": "285px"
}
}
})
Anyway, I wonder, what code snippets do you use?
Top comments (15)
Specially for testing with
Puppeteer
I have some common functions that I reuse in most of the tests likelogin()
ornavigateToProject()
or util functions to get properties from selectors, etc...This is silly but I have a code snippet of
htaccess
to improve wordpress performance. It's just that my brain has never understood Regex :/I also have code snippets for validations and other little things in vanilla
javascript
.We have a few templates we use, and some reusable code snippets.
Stuff like:
Email Validations
Randomise Date Column
Etc...
I've had a discussion about snippets on here somewhere before. But for me and my programming style, I view code snippets as a horror. I can see that they would be useful for some cases, but those are cases I tend to avoid. What I often do is to create types and functions to encapsulate some code, put it in a library, and then reuse it in different projects.
Any reason you are using string index notation (
data["addTo"]
) and not dot notation (data.addTo
)?For example, I could have a key like that;
In this case, I can't use like that
myObject.userName[]
There are many reasons to use index notation.
medium.com/@prufrock123/js-dot-not...
Yeah, but you don't.
There are many reasons not to, as well.
I use them so often I made my own library (github.com/nektro/basalt)
In particular of note, I have (github.com/nektro/basalt/blob/mast...)
This looks much better and cleaner.
"The ones that do no use frameworks, end up making their own square wheel".
You should not have many snippets between projects, engines, frameworks and shared libs yes.
I do have some common nginx config file suited for my projects, and some general python util functions that i need here and there
clg => console.log()
What kind of codes? But I understand you. Sometimes you don't want to spend more times because of the same problems.