function myFunctionName() {
console.log("This function does not accept any inputs.");
console.log("This function does not return any values.");
}
This method returns the element that has the specified ID name.
document.getElementById("myId");
This method returns the elements with the specified CSS class name.
document.getElementsByClassName("myClass");
This method returns the elements with the specified HTML tag .
document.getElementsByTagName("p");
This method returns the first element that matches a specified CSS selector in the document.
document.querySelector("div, #myId");
This method returns all of the elements in the document that match a specified CSS selector.
document.querySelectorAll("div, #myId");
This method creates a new HTML element. But, it does not automatically put the elements onto the page!
var p = document.createElement("p");
p.innerHTML = "New paragraph!";
This method creates a text node to be placed inside of an HTML element.
document.createTextNode("Hello World!");
This method appends a new element as the last child of the parent element.
referenceNode.appendChild(newNode);
Calling this method with an element removes it from the document.
document.getElementById("myId").remove();
See also: DOM removeChild()
This property can be used to set the HTML content of an element.
document.getElementById("myDiv").innerHTML = "Hello World!";
With this, you can write HTML elements directly into the selected element:
document.getElementById("myDiv").innerHTML = "<p>Hello world!</p><p>Two paragraphs !</p>";
You can also use this property to get the contents of an element:
var data = document.getElementById("myDiv").innerHTML;
console.log(data);
This property can be used to get/set the CSS styling of an element.
document.getElementById("myDiv").style.backgroundColor = "red";
Demo: JS variables and functions
Demo: DOM methods
JavaScript variables let you store data values. For example, the following code
var username = prompt("Enter your username");
will call the prompt
method to ask the user for a value,
then store that value in a variable named username. You can also create a variable without giving it a value, making it undefined until something is assigned to it:
var username;
var videoCount = 128;
var temperature = 98.6;
var tempInCelsius = (temperature - 32) * (5.0 / 9.0);
var name = "Nickname";
var blogPost = "Hey all, I'm sorry I haven't posted in so long, it's been such a <b>craaaaazy</b> week. My pet snake Mittens got loose, AGAIN, and I had to stay up all night waiting near the stove and fridge for him to come out. I stayed there for <b>hours</b> and then I open the fridge to get some emergency oatmeal, and you know what??? Mittens slides right into the fridge from the cabinet (??!) while the door's open. And he just. curls up on top of the lettuce and looks at me all like \"closssssse the door\"";
var hasEnteredUsername = false;
function getUsername() {
if (hasEnteredUsername) return;
let username = prompt("Enter a username");
let label = document.createElement("p");
label.innerHTML = "Welcome, " + username;
document.body.appendChild(label);
hasEnteredUsername = true;
}
var candies = ["SweeTarts", "Milk chocolate peanut butter cups", "Twix"];
function printCandies() {
for(let i = 0; i < candies.length; i++) {
console.log("I love eating " + candies[i]);
}
}
var userdata = {
firstName: "Nick",
lastName: "Toothman",
pets: [
{
name: "Banjo",
type: "Cat"
},
{
name: "Daisy",
type: "Dog"
},
{
name: "Dipper",
type: "CatDog"
}
],
speakTo: function (personName) {
alert("Hi, " + personName + "! My name is "
+ this.firstName + " " + this.lastName
+ " and I have " + this.pets.length + " pets");
}
};
We can convert a string read using prompt()
into a number by passing
the value to the Number constructor:
var v1 = prompt("Enter a number");
var n1 = Number(v1);
To get a yes/no answer for whether the input is an actual number, use Number.isNaN:
var actualNumber = Number.isNaN(n1);
if (!actualNumber) {
alert(`n1 is a number: ${n1}`);
}
else {
alert(`n1 is not a number: ${n1}`);
}
Note that we pass n1
into Number.isNaN(), not v1
. Why?
You can convert a number to a string using the .toString() method on the number variable:
var v1 = 37;
var s1 = v1.toString();
Variables declared outside of functions are called global variables. If a variable is global, that means that all scripts and functions on a web page have access to it. Global variables last from the moment that they are declared until the browser window/tab is closed.
Variables declared inside functions are considered local variables. Every time the function is called, its local variables are created and then destroyed when the function is finished.
+, -, *, /, %, ++, --
=, +=, -=, *=, /=, %=
+, +=
==, ===, !=, !==, >, <, >=, <=
This event occurs when the user clicks on an element.
<!-- With HTML -->
<button id="myId" onclick="myFunction()"></button>
<script>
// With JavaScript
document.getElementById("myId").addEventListener("click", myFunction);
// Or this way
document.getElementById("myId").onclick = function() {
/* JavaScript here */
};
</script>
This event occurs when the user double-clicks on an element.
<!-- With HTML -->
<div id="myId" ondblclick="myFunction()"></div>
<script>
// With JavaScript
document.getElementById("myId").addEventListener("dblclick", myFunction);
// Or this way
document.getElementById("myId").ondblclick = function() {
/* JavaScript here */
};
</script>
This event occurs when the mouse pointer is moved onto an element or its children.
<!-- With HTML -->
<div id="myId" onmouseover="myFunction()"></div>
<script>
// With JavaScript
document.getElementById("myId").addEventListener("mouseover", myFunction);
// Or this way
document.getElementById("myId").onmouseover = function() {/* JavaScript here */};
</script>
Try clicking, double-clicking, and putting the mouse over the image:
Transitions allow you to smoothly change between one CSS property and another. Transitions do not work on all properties, however:
This event occurs when there is an error loading an external file (e.g. a document or an image).
<!-- With HTML -->
<img id="myId" onerror="myFunction()">
<script>
// With JavaScript
document.getElementById("myId").addEventListener("error", myFunction);
// Or this way
document.getElementById("myId").onerror = function() {
/* JavaScript here */
};
</script>
This method assigns an event handler to the specified element. One element can have many event handler and there can be more than one event handler for the same type of event.
document.getElementById("myId").addEventListener("click", myFunction);
We've been using prompt() to get input from the user so far, but we can also use input elements. Try entering something in the textbox and clicking the button: