javascript add attribute to object code example
Example 1: javascript update attribute
var element = document.getElementById("elemId");
element.setAttribute("attributeName", "value");
Example 2: how to add property to object in javascript
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
Example 3: put new attribute on html tag using javascript
// Here's what you do for the style attribute
span.setAttribute("style", "width:110%;float:center;left-margin:-10px;top-margin:-10;");
Example 4: how to a property from a JavaScript object
delete myObject.regex;
// or,
delete myObject['regex'];
// or,
var prop = "regex";
delete myObject[prop];
/** Demo */
var myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
delete myObject.regex;
console.log(myObject);
Example 5: Add New Properties to a JavaScript Object
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
myDog.bark = "woof";
// or
myDog["bark"] = "woof";