I am creating elements using jQuery selector.
$(document).ready(function() {
var ss = {
id: "foo",
class: "attack",
dataa: "hhh",
css: {
"color": "red"
}
};
var $div = $("<div>", ss);
$div.html("dfg");
$("body").append($div);
});
Is there a workaround to add json object as attributes using Javascript not jQuery (instead of var $div = $("<div>", ss);
)
Usually I tend to not write all this code for a generic question, but this time this intrigued me.
You can loop through your object properties and for each of them call setAttribute
, a particular case is the style attribute, in this case is built a string.
Code:
var ss = {
id: "foo",
class: "attack",
dataa: "hhh",
css: {
"color": "red"
}
};
var div = document.createElement("div");
function getStyle(o) {
var retString="";
for (var property in o) {
if (o.hasOwnProperty(property)) {
retString += property + ":" + o[property] + ";";
}
}
return retString;
}
function addProps(e, o) {
for (var property in o) {
if (o.hasOwnProperty(property)) {
if (property === 'css') {
e.setAttribute("style", getStyle(o[property]));
} else {
e.setAttribute(property, o[property]);
}
}
}
}
addProps(div, ss);
div.innerHTML = "dfg";
document.body.appendChild(div);
Demo: http://jsfiddle.net/IrvinDominin/wuc439pv/
JavaScript has no native features for creating HTML elements (that all comes from the DOM API).
The DOM API provided by browsers has no native features for taking an object with a bunch of properties that describe attributes and using them to create attributes on an element.
You would need to loop over the object and handle each property in turn (which you could do by calling setAttribute
but you would need to special case css
and dataa
in your example code).
Fiddle DEMO
The javascript
way for adding an attribute to an element is by using setAttribute
method and javascript
way of creating an element
is by using createElement
and below method will provide an overloaded option to setAttribute
that you fetch it as object
:
function setAttributes(el, attrs) {
for(var key in attrs) {
if(key=="css") //if attribute is to set Style and since you are using it as CSS
{
for(var key1 in attrs[key]) //loop through each properties inside that CSS object
{
el.style[key1] = attrs[key][key1] //set Element Style
}
}
else
el.setAttribute(key, attrs[key]); //else just set Attribute
}
}
Below is the complete javascript
version of you above code
$(document).ready(function() {
var ss = {
id: "foo",
class: "attack",
dataa: "hhh",
css: {
"color": "red",
}
};
var $div = document.createElement('div'); //Create element
console.log($div);
setAttributes($div,ss); //use our custom Attribute setting function
$div.innerHTML="dfg";
document.getElementsByTagName('body')[0].appendChild($div)
});
function setAttributes(el, attrs) {
for(var key in attrs) {
if(key=="css")
{
for(var key1 in attrs[key])
{
el.style[key1] = attrs[key][key1]
}
}
else
el.setAttribute(key, attrs[key]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now if you want to replace even $(document).ready
you can replace it with its javascript
equivalent function
as below:
(function() {
// Code placed in document.ready
})();
You can check the console
for properties set to the new Element
I think you want to do the same thing in pure JS form. For this please see the code below -
for(var prop in ss) { // iterates over each property of ss object
div.setAttribute(prop, ss[prop]); // sets an attribute on the div element, first parameter is attr name and second one is its value
}
However, only problem will be the CSS property which is an object. Rest other will be applied as they are using jQuery.
UPDATE: I've found a workaround for this. See below -
for(var prop in ss) {
if(typeof ss[prop] !== 'object') { // confirms property is NOT an object
div.setAttribute(prop, ss[prop]);
}
else { // if the property is object
div.setAttribute(prop, '');
var val = '';
for(var p in ss[prop]) { // iterate through the properties of the object
val += p+":"+ss[prop][p]+';'; // concatenate them all in one
}
div.setAttribute(prop, val); // and finally set the attribute
}
}
Here is the working example (using Pure JS).
Full Snippet:
var ss = {
id: "foo",
class: "attack",
dataa: "hhh",
style: {
"color": "red",
"font-size": "50px"
}
};
var div = document.createElement('div');
div.innerHTML = 'dsdf';
for (var prop in ss) {
if (typeof ss[prop] !== 'object') {
div.setAttribute(prop, ss[prop]);
} else {
div.setAttribute(prop, '');
var val = '';
for (var p in ss[prop]) {
val += p + ":" + ss[prop][p] + ';';
}
div.setAttribute(prop, val);
}
}
document.body.appendChild(div);
You can create function for adding elements:
function createElement(element, attributes, innerHtml, parent) {
element = element || 'div';
attributes = attributes || {};
innerHtml = innerHtml || '';
parent = parent || document.body;
var elem = document.createElement(element);
elem.innerHTML = innerHtml;
for(var attr in attributes) {
elem.setAttribute(attr, attributes[attr]);
}
parent.appendChild(elem);
}
createElement('div', {
id: "foo",
class: "attack",
dataa: "hhh",
css: {
"color": "red"
}
})
http://jsfiddle.net/rtbpn6vy/1/
Firebase Cloud Functions: PubSub, "res.on is not a function"
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
Here in click. html,OnClick of clint_ip text box is redirecting to index.
I have these JavaScript function that runs every time on every pageload and postback. How do I change the settings of this function to make it run only during the 1st load of the webpage and not every postback?.
So I was able to create a slideshow using the jquery backstretch. .
I want show/hide some categories in highcharts using checkbox, can you help me? This is my code so far:.