Learn JavaScript: 6 Tutorials
Learn JavaScript: 6 Tutorials
Opensource.com
We are Opensource.com
Do you have an open source story to tell? Submit a story idea at opensource.com/story
Email us at [email protected]
Table of Contents
Learn JavaScript by writing a guessing game....................................................................................3
Write your first JavaScript code..........................................................................................................12
Create a JavaScript API in 6 minutes.................................................................................................18
How much JavaScript do you need to know before learning ReactJS?.......................................24
Code your first React UI app...............................................................................................................27
4 steps to set up global modals in React..........................................................................................33
How I build command-line apps in JavaScript.................................................................................40
165+ JavaScript terms you need to know.........................................................................................43
Learn JavaScript by writing a
guessing game
By Mandy Kendall
It's pretty safe to say that most of the modern web would not exist without JavaScript. It's
one of the three standard web technologies (along with HTML and CSS) and allows anyone
to create much of the interactive, dynamic content we have come to expect in our
experiences with the World Wide Web. From frameworks like React to data visualization
libraries like D3, it's hard to imagine the web without it.
There's a lot to learn, and a great way to begin learning this popular language is by writing a
simple application to become familiar with some concepts. Recently, some Opensource.com
correspondents have written about how to learn their favorite language by writing a simple
guessing game, so that's a great place to start!
Getting started
JavaScript comes in many flavors, but I'll start with the basic version, commonly called "Vanilla
JavaScript." JavaScript is primarily a client-side scripting language, so it can run in any
standard browser without installing anything. All you need is a code editor (Brackets is a great
one to try) and the web browser of your choice.
Use a few basic HTML tags in this file to display the game's title, instructions for how to play,
interactive elements for the player to use to enter and submit their guesses, and a
placeholder for providing feedback to the player:
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8" />
<title> JavaScript Guessing Game </title>
</head>
<body>
<h1>Guess the Number!</h1>
<p>I am thinking of a number between 1 and 100. Can you guess what it is?
</p>
<label for="guess">My Guess</label>
<input type="number" id="guess">
<input type="submit" id="submitGuess" value="Check My Guess">
<p id="feedback"></p>
</body>
</html>
The <h1> and <p> elements let the browser know what type of text to display on the page.
The set of <h1> tags signifies that the text between those two tags (Guess the Number!)
is a heading. The set of <p> tags that follow signify that the short block of text with the
instructions is a paragraph. The empty set of <p> tags at the end of this code block serve as a
placeholder for the feedback the game will give the player based on their guess.
Now, you can start to write your JavaScript between these two script tags. The final file looks
like this:
<!DOCTYPE>
<html>
<head>
To run this in the browser, either double-click on the file or go to the menu in your favorite
web browser and choose File > Open File. (If you are using Brackets, you can also use the
lightning-bolt symbol in the corner to open the file in the browser).
Math has properties and functions for working with mathematical concepts in JavaScript. You
will use two Math functions to generate the random number for your player to guess.
For this game, set the random number between 1 and 100 to narrow down the player's options.
Take the decimal you just generated and multiply it by 100 to produce a decimal between 0
and…not quite 100. But you'll take care of that in a few more steps.
Right now, your number is still a decimal, and you want it to be a whole number. For that, you
can use another function that is part of the Math object, Math.floor(). Math.floor()'s purpose
is to return the largest integer that is less than or equal to the number you give it as an
argument—which means it rounds down to the nearest whole number:
Math.floor(Math.random() * 100)
That leaves you with a whole number between 0 and 99, which isn't quite the range you want.
You can fix that with your last step, which is to add 1 to the result. Voila! Now you have a
(somewhat) randomly generated number between 1 and 100:
Math.floor(Math.random() * 100) + 1
Variables
Now you need to store the randomly generated number so that you can compare it to your
player's guesses. To do that, you can assign it to a variable.
JavaScript has different types of variables you can choose, depending on how you want to
use the variable. For this game, use const and let.
• let is used for variables if their value can change throughout the code.
• const is used for variables if their value should not be changed.
There's a little more to const and let, but this is all you need to know for now.
The random number is generated only once in the game, so you will use a const variable to
hold the value. You want to give the variable a name that makes it clear what value is being
stored, so name it randomNumber:
const randomNumber
Most browsers include Developer Tools that you can open by pressing the F12 key on your
keyboard. From there, you should see a tab labeled Console. Any information logged to the
console will appear here. Since the code you have written so far will run as soon as the
browser loads, if you look at the console, you should see the random number that you just
generated! Hooray!
Depending on the JavaScript version you are using, there are many different ways to write, or
declare, a function. Since this is an introduction to the language, declare your function using
the basic function syntax.
Start with the keyword function and then give the function a name. It's good practice to use
a name that is an action that describes what the function does. In this case, you are checking
the player's guess, so an appropriate name for this function would be checkGuess. After the
function name, write a set of parentheses and then a set of curly braces. You will write the
body of the function between these curly braces:
function checkGuess() {}
JavaScript can get the number the player enters into the number input field by accessing its
value. You can do this by referring to the element's id and adding .value to the end. This
time, use a let variable to hold the value of the user's guess:
Whatever number the player enters into the number input field will be assigned to the
myGuess variable in the checkGuess function.
You can decide what feedback the player will receive by using a series of conditional
statements. A conditional statement checks to see if a condition is met before running a
code block. If the condition is not met, the code stops, moves on to check the next condition,
or continues with the rest of the code without running the code in the conditional block:
The first conditional block compares the player's guess to the random number the game
generates using a comparison operator ===. The comparison operator checks the value on
the right, compares it to the value on the left, and returns the boolean true if they match and
false if they don't.
If the number matches (yay!), make sure the player knows. To do this, manipulate the DOM by
adding text to the <p> tag that has the id attribute "feedback." This works just like
guess.value above, except instead of getting information from the DOM, it changes the
information in it. <p> elements don't have a value like <input> elements—they have text
instead, so use .textContent to access the element and set the text you want to display:
Of course, there is a good chance that the player didn't guess right on the first try, so if
myGuess and randomNumber don't match, give the player a clue to help them narrow down
their guesses. If the first conditional fails, the code will skip the code block in that if
statement and check to see if the next condition is true. That brings you to your else if
blocks:
If you were to read this as a sentence, it might be something like this: "If the player's guess is
equal to the random number, let them know they got it right. Otherwise (else), check if the
player's guess is greater than randomNumber, and if it is, display the player's guess and tell
them it was too high."
The last possibility is that the player's guess was lower than the random number. To check
that, add one more else if block:
The code to generate the random number and log it to the console is outside of a function, so
it will run automatically when the browser loads your script. However, for the code inside your
function to run, you have to call it.
There are several ways to call a function. Here, you want the function to run when the player
clicks on the "Check My Guess" button. Clicking a button creates a user event, which the
JavaScript code can then "listen" for so that it knows when it needs to run a function.
The last line of code adds an event listener to the button to "listen" for when the button is
clicked. When it "hears" that event, it will run the function assigned to the event listener:
submitGuess.addEventListener('click', checkGuess)
You have already seen a function that takes parameters, but take a moment to look at how
this works. Parameters are information that a function needs to perform its task. Not all
functions need parameters, but the addEventListener function needs two. The first
parameter it takes is the name of the user event for which it will listen. The user can interact
with the DOM in many ways, like typing, moving the mouse, tabbing with the keyboard, or
copying and pasting text. In this case, the user event you are listening for is a button click, so
the first parameter will be click.
The second piece of information addEventListener needs is the name of the function to
run when the user clicks the button. In this case, it's the checkGuess function.
Now, when the player presses the "Check My Guess" button, the checkGuess function will
get the value they entered in the number input field, compare it to the random number, and
display feedback in the browser to let the player know how they did. Awesome! Your game is
ready to play.
By Seth Kenlon
JavaScript is a programming language full of pleasant surprises. Many people first encounter
JavaScript as a language for the web. There's a JavaScript engine in all the major browsers,
there are popular frameworks such as JQuery, Cash, and Bootstrap to help make web design
easier, and there are even programming environments written in JavaScript. It seems to be
everywhere on the internet, but it turns out that it's also a useful language for projects like
Electron, an open source toolkit for building cross-platform desktop apps with JavaScript.
Install JavaScript
As you progress with JavaScript, you may find yourself wanting advanced JavaScript libraries
and runtimes. When you're just starting, though, you don't have to install JavaScript at all. All
major web browsers include a JavaScript engine to run the code. You can write JavaScript
using your favorite text editor, load it into your web browser, and see what your code does.
<html>
<head>
<title>JS</title>
</head>
To add JavaScript to this simple HTML page, you can either create a JavaScript file and refer
to it in the page's head or just embed your JavaScript code in the HTML using the <script>
tag. In this example, I embed the code:
<html>
<head>
<title>JS</title>
</head>
<body>
<p id="example">Nothing here.</p>
<script>
let myvariable = "Hello world!";
document.getElementById("example").innerHTML = myvariable;
</script>
</body>
</html>
As you can see, the <p> tag as written still contains the string "Nothing here," but when it's
rendered, JavaScript alters it so that it contains "Hello world" instead. Yes, JavaScript has the
power to rebuild (or just help build) a webpage.
The JavaScript in this simple script does two things. First, it creates a variable called
myvariable and places the string "Hello world!" into it. Finally, it searches the current
document (the web page as the browser is rendering it) for any HTML element with the ID
example. When it locates example, it uses the innerHTML function to replace the contents
of the HTML element with the contents of myvariable.
Of course, using a custom variable isn't necessary. It's just as easy to populate the HTML
element with something being dynamically created. For instance, you could populate it with a
timestamp:
<html>
<head>
<title>JS</title>
</head>
<body>
<p id="example">Date and time appears here.</p>
<script>
document.getElementById("example").innerHTML = Date();
</script>
</body>
</html>
Reload the page to see a timestamp generated at the moment the page is rendered. Reload a
few times to watch the seconds increment.
Words (or "strings") must be enclosed in quotation marks ("), while numbers (or "integers")
go without.
Almost everything else is a convention of the JavaScript language, such as variables, arrays,
conditional statements, objects, functions, and so on.
JavaScript's built-in typeof function can help you identify what kind of data a variable
contains. Using the first example, you can find out what kind of data myvariable contains by
modifying the displayed text to:
<string>
let myvariable = "Hello world!";
document.getElementById("example").innerHTML = typeof(myvariable);
</string>
This renders "string" in your web browser because the variable contains "Hello world!" Storing
different kinds of data (such as an integer) in myvariable would cause a different data type
to be printed to your sample web page. Try changing the contents of myvariable to your
favorite number and then reloading the page.
Here's a simple web page featuring a resized image and a button that analyzes the image and
returns the true image dimensions. In this example code, the <button> HTML element uses
the built-in JavaScript function onclick to detect user interaction, which triggers a custom
function called get_size:
<html>
<head>
<title>Imager</title>
</head>
<body>
<div>
<button onclick="get_size(document.getElementById('myimg'))">
Get image size
</button>
</div>
<div>
<img style="width: 15%" id="myimg" src="penguin.png" />
</div>
<script>
function get_size(i) {
let w = i.naturalWidth;
let h = i.naturalHeight;
alert(w + " by " + h);
}
</script>
</body>
</html>
Save the file and load it into your web browser to try the code.
Learning JavaScript is easy and fun. There are lots of websites with tutorials available. There
are also over a million JavaScript libraries to help you interface with devices, peripherals, the
Internet of Things, servers, file systems, and lots more. And as you're learning, keep
our JavaScript cheat sheet close by so you remember the fine details of syntax and
structure.
By Jessica Cherry
This article demonstrates creating a base API with Express and JavaScript. Express is a
NodeJS minimalist web framework. This combination allows for minimal effort to get an API
up and running at the speed of light. If you have six minutes of free time, you can get this API
working to do something useful.
$ mkdir test-api
The npm init command creates the package JSON for our project below. Type npm init
and press enter several times. The output is shown below:
$ npm init
Press ^C at any time to quit.
package name: (test-api)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
This utility walks you through creating a package.json file. It only covers the most common
items, and tries to guess sensible defaults. See npm help init for definitive
documentation on these fields and exactly what they do.
Use npm install {pkg} afterward to install a package and save it as a dependency in the
package.json file.
Finally, create your source directory and your index.js file, which is where the application
code lives:
$ mkdir src
$ touch src/index.js
Time to code!
Each of these constant variables is available in the scopes below. Because you're not using the
following scopes within the code, these constants are used without too much extra thought.
When you call app.get, you define the GET{rest article needed} endpoint to a
forward slash. This also sets the "hello world" response.
Finally, in the last section, you will start your app on port 5000. The output on your terminal
shows your defined message in a file called console.log.
To start your application, run the following command, and see the output as shown:
$ node ./src/index.js
Example app listening on port 5000
Next, check out what HTTPie says about the API call:
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 12
Content-Type: text/html; charset=utf-8
Date: Tue, 21 Jun 2022 14:31:06 GMT
ETag: W/"c-Lve95gjOVATpfV8EL5X4nxwjKHE"
Keep-Alive: timeout=5
X-Powered-By: Express
Hello World!
And there you have it! One whole working API call. So what's next? Well, you could try some
changes to make it more interesting.
Aside from a GET command in your code, you now have a POST to make some changes to
your count. With count defined as 0, the LET command allows changes to the COUNT variable.
In app.get, you get the count, and in app.post, you ++count, which counts upwards in
increments of 1. When you rerun the GET, you receive the new number.
Next, use HTTPie to run the GET and POST operations for a test to confirm it works. Starting
with GET, you can grab the count:
As you can see, the count goes up! Run one more GET operation and see what the output is:
By Sachin Samal
React is a UI framework built on top of HTML, CSS, and JavaScript, where JavaScript (JS) is
responsible for most of the logic. If you have knowledge of variables, data types, array
functions, callbacks, scopes, string methods, loops, and other JS DOM manipulation-related
topics, these will tremendously speed up the pace of learning ReactJS.
Your concept of modern JavaScript will dictate the pace of how soon you can get going with
ReactJS. You don't need to be a JavaScript expert to start your ReactJS journey, but just as
knowledge of ingredients is a must for any chef hoping to master cooking, the same is true for
learning ReactJS. It's a modern JavaScript UI library, so you need to know some JavaScript.
The question is, how much?
Example explanation
Suppose I'm asked to write an essay about a "cow" in English, but that I know nothing about
the language. In this case, for me to successfully complete the task, I should not only have an
idea about the topic but also the specified language.
Assuming that I acquire some knowledge about the topic (a cow), how can I calculate the
amount of English I need to know to be able to write about the proscribed topic? What if I
have to write an essay on some other complex topics in English?
It’s difficult to figure that out, isn’t it? I don’t know what things I'm going to write about the
topic, but it could be anything. So to get started, I have to have a proper knowledge of the
English language, but it doesn't end there.
• variables
• data types
• string methods
• loops
• conditionals
You should be familiar with these specifically in JavaScript. But these are just the bare
minimum prerequisites. When you try to create a simple React app, you'll inevitably need to
handle events. So, the concept of normal functions, function expressions, statements, arrow
function, the difference between an arrow function and a regular function, and the lexical
scoping of this keyword in both types of function is really important.
But the question is, what if I have to create a complex app using ReactJS?
Get inspired
Handling events, spread operators, destructuring, named imports, and default imports in
JavaScript will help you understand the working mechanism of React code.
Most importantly, you must understand the core concepts behind JavaScript itself. JavaScript
is asynchronous by design. Don't be surprised when code appearing at the bottom of a file
executes before code at the top of the file does. Constructs like promises, callbacks, async-
await, map, filter, and reduce, are the most common methods and concepts in ReactJS,
especially when developing complex applications.
Getting good
It's easy for me to say what you need to know, but it's something else entirely for you to go
learn it. Practicing a lot of JavaScript is essential, but you might be surprised that I don't think
it means you necessarily have to wait until you master it. There are certain concepts that are
important beforehand, but there's a lot you can learn as you go. Part of practicing is learning,
so you get started with JavaScript and even with some of the basics of React, as long as you
move at a comfortable pace and understand that doing your "homework" is a requirement
before you attempt anything serious.
By Jessica Cherry
Who wants to create their first UI app? I do, and if you're reading this article, I assume you do,
too. In today's example, I'll use some JavaScript and the API with Express I demonstrated in
my previous article. First, let me explain some of the tech you're about to use.
What is React?
React is a JavaScript library for building a user interface (UI). However, you need more than
just the UI library for a functional UI. Here are the important components of the JavaScript
web app you're about to create:
Preconfiguration
If you haven't already, look at my previous article. You'll use that code as part of this React
app. In this case, you'll add a service to use as part of the app. As part of this application, you
have to use the npx package to create the new folder structure and application:
As you can see, the npx command has created a new template with a folder structure, an
awesome README file, and a Git repository. Here's the structure:
$ cd count-ui/
/Users/cherrybomb/count-ui
$ ls -A -1
.git
.gitignore
README.md
node_modules
package-lock.json
package.json
public
src
This process also initialized the Git repo and set the branch to master, which is a pretty cool
trick. Next, install the npm packages:
Now that those are set up, add your services, and main.js file:
$ mkdir src/services
src/services
$ touch src/services/main.js
This process creates a JavaScript file that interacts with the API you created in my previous
article.
$ touch src/setupProxy.js
In this code, the app.use function specifies the service to use as /api when connecting to
the existing API project. However, nothing defines api in the code. This is where a proxy
comes in. With a proxy, you can define the api function on the proxy level to interact with
your Express API. This middleware registers requests between both applications because the
JavaScript imports
In your base src directory, you see that the original template created an App.js, and you
must add main.js (in the services directory) to your imports in the App.js file. You also
need to import React on the very first line, as it is external to the project:
function App() {
const [count, setCount] = React.useState(0);
React.useEffect(()=>{
async function fetchCount(){
const newCount = (await main.get()).data.count;
setCount(newCount);
}
fetchCount();
}, [setCount]);
return (
<div className="App">
<header className="App-header">
<h4>
{count}
</h4>
<button onClick={async ()=>{
setCount((await main.increment()).data.count);
}}>
Increment
</button>
</header>
</div>
);
}
Once everything is running, open your browser to localhost:5000 to see the front end has
a nice, admittedly minimal, page with a button:
What happens when you press the button? (Or, in my case, press the button several times.)
Congratulations, you now have a React app that uses your new API.
By Ajay Pratap
A modal dialog is a window that appears on top of a web page and requires a user's
interaction before it disappears. React has a couple of ways to help you generate and manage
modals with minimal coding.
If you create them within a local scope, you must import modals into each component and
then create a state to manage each modal's opening and closing status.
By using a global state, you don't need to import modals into each component, nor do you
have to create a state for each. You can import all the modals in one place and use them
anywhere.
In my opinion, the best way to manage modal dialogs in your React application is globally by
using a React context rather than a local state.
In this code, all dialog components are mapped with the modal type. The showModal and
hideModal functions are used to open and close dialog boxes, respectively.
The showModal function takes two parameters: modalType and modalProps. The
modalProps parameter is optional; it is used to pass any type of data to the modal as a prop.
The hideModal function doesn't have any parameters; calling it causes the current open
modal to close.
This has a custom hook, useGlobalModalContext, that provides store object from where
you can access all the props and the functions showModal and hideModal. You can close
the modal by using the hideModal function.
To update a modal, create a file called UpdateModal.tsx and add this code:
import "@patternfly/react-core/dist/styles/base.css";
import "./fonts.css";
import { GlobalModal } from "./components/GlobalModal";
import { AppLayout } from "./AppLayout";
export default function App() {
return (
<GlobalModal>
<AppLayout />
</GlobalModal>
);
}
App.tsx is the top-level component in your app, but you can add another
component according to your application's structure. However, make sure it is one level above
where you want to access modals.
There are three buttons in the AppLayout component: create modal, delete modal, and
update modal. Each modal is mapped with the corresponding modalType: CREATE_MODAL,
DELETE_MODAL, or UPDATE_MODAL.
If you'd like to see the code in action, I've included the complete application I created for this
article in a sandbox.
JavaScript is a language developed for the web, but its usefulness has gone far beyond just
the Internet. Thanks to projects like Node.js and Electron, JavaScript is as much a general-
purpose scripting language as a browser component. There are JavaScript libraries specially
designed to build command-line interfaces. Yes, you can run JavaScript in your terminal.
Now, when you enter a command into your terminal, there are generally options, also called
switches or flags, that you can use to modify how the command runs. This is a useful
convention defined by the POSIX specification, so as a programmer, it's helpful to know how
to detect and parse the options. To get this functionality from JavaScript, it's useful to use a
library designed to make it easy to build command-line interfaces. My favorite is
Commander.js. It's easy, it's flexible, and it's intuitive.
Installing node
To use the Commander.js library, you must have Node.js installed. On Linux, you can install
Node using your package manager. For example, on Fedora, CentOS, Mageia, and others:
On Windows and macOS, you can download installers from the nodejs.org website.
Installing Commander.js
To install Commander.js, use the npm command:
program
.description('A sample application to parse options')
.option('-a, --alpha', 'Alpha')
.option('-b, --beta <VALUE>', 'Specify a VALUE', 'Foo');
The first option, which I've called --alpha (-a for short), is a Boolean switch: It either exists
or it doesn't. It takes no arguments. The second option, which I've called --beta (-b for
short), accepts an argument and even specifies a default value when you've provided nothing.
program.parse();
const options = program.opts();
console.log('Options detected:');
if (options.alpha) console.log('alpha');
const beta = !options.beta ? 'no' : options.beta;
console.log('beta is: %s', beta);
$ node ./example.js
Options detected:
beta is: Foo
This time, the test script successfully detected the option --alpha, and the --beta option
with the value provided by the user.
Option parsing
Here's the full demonstration code for your reference:
Including options for your users is an important feature for any application, and Commander.js
makes it easy to do. There are other libraries aside from Commander.js, but I find this one easy
and quick to use. What's your favorite JavaScript command-line builder?
By Sachin Samal
JavaScript variables
var: The most used variable. Can be reassigned but only accessed within a function, meaning
function scope. Variables defined with var move to the top when code is executed.
const: Cannot be reassigned and not accessible before they appear within the code,
meaning block scope.
let: Similar to const with block scope, however, the let variable can be reassigned but not
re-declared.
Data types
Numbers: var age = 33
Variables: var a
Operations: var b = 4 + 5 + 6
Objects
This is a simple example of objects in JavaScript. This object describe the variable car, and
includes keys or properties such as make, model, and year are the object's property names.
Each property has a value, such as Nissan, Altima, and 2022. A JavaScript object is a
collection of properties with values, and it functions as a method.
var car = {
make:"Nissan",
model:"Altima",
year:2022,
};
Comparison operators
==: Is equal to
?: Ternary operator
Logical operators
&&: Logical AND
||: Logical OR
!: Logical NOT
Output data
alert(): Output data in an alert box in the browser window
Array methods
Array: An object that can hold multiple values at once.
join(): Combine elements of an array into a single string and return the string
lastIndexOf(): Give the last position at which a given element appears in an array
valueOf(): Return the first position at which a given element appears in an array
JavaScript loops
Loops: Perform specific tasks repeatedly under applied conditions.
do while: Similar to the while loop, it executes at least once and performs a check at the
end to see if the condition is met. If it is, then it executes again
if-else statements
An if statement executes the code within brackets as long as the condition in parentheses is
true. Failing that, an optional else statement is executed instead.
if (condition) {
// do this if condition is met
} else {
// do this if condition is not met
}
Strings
String methods
charAt(): Return a character at a specified position inside a string
fromCharCode(): Return a string created from the specified sequence of UTF-16 code units
indexOf(): Provide the position of the first occurrence of a specified text within a string
lastIndexOf(): Same as indexOf() but with the last occurrence, searching backwards
search(): Execute a search for a matching text and return its position
valueOf(): Return the primitive value (that has no properties or methods) of a string object
Number methods
toExponential(): Return a string with a rounded number written as exponential notation
Math methods
abs(a): Return the absolute (positive) value of a
exp(a): Value of Ex
Date(2022, 6, 22, 4, 22, 11, 0): Create a custom date object. The numbers
represent year, month, day, hour, minutes, seconds, milliseconds. You can omit anything
except for year and month.
getUTCDate(): Day (date) of the month in the specified date according to universal time
(also available for day, month, full year, hours, minutes, etc.)
parse: Parse a string representation of a date and return the number of milliseconds since
January 1, 1970
setUTCDate(): Set the day of the month for a specified date according to universal time
(also available for day, month, full year, hours, minutes, etc.)
Dom mode
Node methods
appendChild(): Add a new child node to an element as the last child node
hasChildNodes(): Return true if an element has any child nodes, otherwise false
insertBefore(): Insert a new child node before a specified, existing child node
normalize(): Join adjacent text nodes and removes empty text nodes in an element
Element methods
getAttribute(): Return the specified attribute value of an element node
getAttributeNS(): Return string value of the attribute with the specified namespace and
name
getAttributeNodeNS(): Return the attribute node for the attribute with the given
namespace and name
getElementsByTagName(): Provide a collection of all child elements with the specified tag
name
removeAttributeNode(): Take away a specified attribute node and return the removed
node
setAttributeNS(): Add a new attribute or changes the value of an attribute with the given
namespace and name
JavaScript events
Mouse
onclick: User clicks on an element
onmouseout: User moves the mouse pointer out of an element or one of its children
onplaying: Media is playing after having been paused or stopped for buffering