Objects let us store a collection of properties.
var objectName = {
propertyName: propertyValue,
propertyName: propertyValue,
...
};
var aboutMe = {
hometown: 'Atlanta, GA',
hair: 'Auburn',
likes: ['knitting', 'code'],
birthday: {month: 10, day: 17}
};
You can retrieve values using "dot notation"
var aboutMe = {
hometown: 'Atlanta, GA',
hair: 'Auburn'
};
var myHometown = aboutMe.hometown;
Or using "bracket notation" (like arrays)
var myHair = aboutMe['hair'];
You can use dot or bracket notation to change properties
var aboutMe = {
hometown: 'Atlanta, GA',
hair: 'Auburn'
};
aboutMe.hair = 'blue';
Add new properties
aboutMe.gender = 'female';
Or delete them
delete aboutMe.gender;
Since arrays can hold any data type, they can also hold objects
var myCats = [
{name: 'Lizzie',
age: 18},
{name: 'Daemon',
age: 1}
];
for (var i = 0; i < myCats.length; i++) {
var myCat = myCats[i];
console.log(myCat.name + ' is ' + myCat.age + ' years old.');
}
Just like other data types, objects can be passed into functions:
var lizzieTheCat = {
age: 18,
furColor: 'grey',
likes: ['catnip', 'milk'],
birthday: {month: 7, day: 17, year: 1996}
}
function describeCat(cat) {
console.log('This cat is ' + cat.age + ' years old with ' + cat.furColor + ' fur.');
}
describeCat(lizzieTheCat);
Create an object to hold information on your favorite recipe. It should have properties for recipeTitle (a string), servings (a number), and ingredients (an array of strings).
Try displaying some information about your recipe.
Bonus: Create a loop to list all the ingredients.
Objects can also hold functions.
var lizzieTheCat = {
age: 18,
furColor: 'grey',
meow: function() {
console.log('meowww');
},
eat: function(food) {
console.log('Yum, I love ' + food);
},
};
Call object methods using dot notation.
lizzieTheCat.meow();
lizzieTheCat.eat('brown mushy stuff');
JS provides several built-in objects:
A website is a way to present your content to the world, using HTML and CSS to present that content & make it look good.
The "#" is how you tell CSS "this is an id."
The "." is how you tell CSS "this is a class name."
We model the nested structure of an HTML page with the DOM (Document Object Model) Tree. The browser makes a "map" of all the elements on a page.
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<style>
h1 {
color: red;
}
</style>
</head>
<body>
<h1>My Page</h1>
<p>Hello World!</p>
<img src="http://placekitten.com/200/300" alt="cat"/>
</body>
</html>
Your browser automatically builds a Document Object to store the DOM of a page. To change a page:
You can find nodes by id using the method:
document.getElementById(id);
To find:
<img id="kittenPic" src="http://placekitten.com/200/300" alt="cat"/>
We would use:
var imgKitten = document.getElementById('kittenPic');
You can find certain types of HTML elements using this method:
document.getElementsByTagName(tagName);
To find:
<li>Daisy</li>
<li>Tulip</li>
We would use:
var listItems = document.getElementsByTagName('li');
for (var i = 0; i < listItems.length; i++) {
var listItem = listItems[i];
}
In newer browsers, you can use other methods too.
Available in IE9+, FF3.6+, Chrome 17+, Safari 5+:
document.getElementsByClassName(className);
Available in IE8+, FF3.6+, Chrome 17+, Safari 5+:
document.querySelector(cssQuery);
document.querySelectorAll(cssQuery);
Any method that starts with "getElement" will return a single node.
document.getElementById('uniqueID'); //returns a single node
Any method that starts with "getElements" will return a array of nodes. To modify a single node, you will need to use bracket notation to select the correct one.
document.getElementsByTagName('p'); //returns multiple nodes
var specficParagraph = document.getElementsByTagName('p')[2];
You can access and change attributes of DOM nodes using dot notation.
To change this element:
<img id="kittenPic" src="http://placekitten.com/200/300" alt="cat"/>
We could change the src attribute this way:
var imgKitten = document.getElementById('kittenPic');
var oldSrc = imgKitten.src;
imgKitten.src = 'http://placekitten.com/100/500';
You can also use getAttribute/setAttribute:
<img id="kittenPic" src="http://placekitten.com/200/300" alt="cat"/>
We could change the src attribute this way:
var imgKitten = document.getElementById('kittenPic');
var oldSrc = imgKitten.getAttribute('src');
imgKitten.setAttribute('src', 'http://placekitten.com/100/500');
You can change page css using style
To make this CSS:
body {
color: red;
}
Use this JavaScript:
var pageNode = document.getElementsByTagName('body')[0];
pageNode.style.color = 'red';
Change any CSS property with a "-" to camelCase, and be sure to include a unit on any number
To make this CSS:
body {
background-color: pink;
padding-top: 10px;
}
Use this JavaScript:
var pageNode = document.getElementsByTagName('body')[0]
pageNode.style.backgroundColor = 'pink';
pageNode.style.paddingTop = '10px';
Create a simple HTML page or use this sample code.
Isolate a node (an element on the page) and change an attribute or add a new style.
Each DOM node has an innerHTML
property with the HTML of all its children. You can use the property to view or change the HTML of a node.
For example, you can overwrite the entire body:
var pageNode = document.getElementsByTagName('body')[0];
pageNode.innerHTML = '<h1>Oh Noes!</h1> <p>I just changed the whole page!</p>'
Or just add some new content to the end:
pageNode.innerHTML += '...just adding this bit at the end of the page.';
You can also target a particular element
To fill this HTML element:
<p id="warning"></p>
We can select the node and modify it:
var warningParagraph = document.getElementById('warning');
warningParagraph.innerHTML = 'Danger Will Robinson!';
The document
object also provides ways to create nodes from scratch:
document.createElement(tagName);
document.createTextNode(text);
document.appendChild();
var pageNode = document.getElementsByTagName('body')[0];
var newImg = document.createElement('img');
newImg.src = 'http://placekitten.com/400/300';
newImg.style.border = '1px solid black';
pageNode.appendChild(newImg);
var newParagraph = document.createElement('p');
var paragraphText = document.createTextNode('Squee!');
newParagraph.appendChild(paragraphText);
pageNode.appendChild(newParagraph);
Create a new paragraph element and add it to a div on your page.