Javascript and the DOM
JavaScript
Javascript can access style sheets and style properties via the Document Object Model (DOM). Javascript can be used to set styles via the style object on an element or to read current styling information (used values) via the getComputedstyle method.
You can also use Javascript to read the contents of style sheets via the document.styleSheets object, which is a useful technique for creating bridge libraries to bring support for unsupported CSS properties or selectors to older browsers.
Defining the Document Object
The document object is an object that is created by the browser for each new HTML page (document) that is viewed. By doing this, JavaScript gives you access to a number of properties and methods that can affect the document in various ways.
You have been using the write() method of the document object for quite some time in this book. This method allows you to write a string of text into an HTML document.
To begin your journey through the document object, you will take a look at the Document Object Model (DOM) and the various properties you can access with this object. Many of these properties will turn out to be quite useful when writing scripts.
Using the Document Object Model
The Document Object Model (DOM) allows JavaScript (and other scripting languages) to access the structure of the document in the browser. Each document is made up of structured nodes (for example, the body tag would be a node, and any elements within the body element would be child nodes of the body element). With this structure in place, a scripting language can access the elements within the document in a number of ways, allowing for the modification of the elements within the document.
Javascript: the Basics
As with a number of things on the Web, there’s more than one way to do it. You can mix your Javascript code right in with your HTML markup, or you can separate it completely and store your scripts in separate files. In the following sections, you’ll look at three different ways to implement Javascript within your pages: linking, embedding, or putting code inline. Whenever possible, it’s best to try to keep your Javascript separated from your markup—but sometimes, it may be appropriate to use inline code if you’re developing an idea and need to quickly mock something up.
linking code (separating form from function)
Javascript files are typically given a .js file extension. They are just plain-text files containing any bits of Javascript code you’d like. These files can then be linked to in either the <head> or <body> of your pages:
this is definitely the best-practice approach because it creates a clear separation between the content contained in your markup and any interactivity or behaviors that you’re including in your pages. Taking this approach, you can then call any functions defined in the script.js file on any number of pages (that contain a link to script.js) and reuse those functions throughout your entire website.
Embedding Javascript
Your second option is to embed the actual Javascript code in your page. this is a less desirable option for a couple of reasons: there is less separation between form and function. You are also throwing away one of the great benefits to Javascript’s object oriented nature: code reuse. Let’s say you write a function to check to make sure a text box on a form isn’t left empty (a common practice when you’re validating a form’s input). If you embed that function in a page, that function can be called only from within that page. You would have to rewrite it (or at the very least copy and paste it) into any other pages that required similar functionality. this concept might seem familiar to you: it’s similar to the way CSS works. If you put your style declarations in a page, as opposed to just linking/importing them from an external file, you’ll find yourself doing a lot more typing. Nevertheless, sometimes when you’re working out the bugs of a tricky piece of code, it’s handy to have it embedded right in your page so that you do not have to flip between multiple text editors. Here’s how you would embed Javascript into an HTML page:
function checkTextBox () {
/* Some code */
}
</script>
Embedding Javascript in the <head> and embedding Javascript in the <body> are no different from one another. It’s simply a matter of choice: some developers like to keep related code together, whereas others think that all scripts should be grouped together in the <head> so that you know exactly where to look instead of hunting through markup. If you’re going to embed your Javascript, try to pick one convention and stick to it.
Inline Javascript
Again, one step down the ladder of properly separating form from function is putting Javascript inline. this is definitely the worst way to do it, because your code is completely isolated to a particular place and cannot be reused in other places. that said, if you’re just trying to work out a functional mock-up of something and you don’t want to bother with defining functions and such, a little inline scripting might just do what you need (just be sure to clean it up before you launch the site!).
Javascript Style Guide and Coding Conventions
Always use the same coding conventions for all your Javascript projects.
Javascript Coding Conventions
Coding conventions are style guidelines for programming. they typically cover:
- Naming and declaration rules for variables and functions.
- Rules for the use of white space, indentation, and comments.
- Programming practices and principles
- Make code maintenance easier
Coding conventions can be documented rules for teams to follow, or just be your individual coding practice.
![]() |
this page describes the general Javascript code conventions used by
W3Schools. You should also read the next chapter "Best Practices", and learn how to avoid coding pitfalls. |
---|
Variable Names
At W3schools we use camelCase for identifier names (variables and functions).
All names start with a letter.
At the bottom of this page, you will find a wider discussion about naming rules.
lastName = "Doe";
price = 19.90;
tax = 0.20;
fullPrice = price + (price * tax)
Spaces Around Operators
Always put spaces around operators ( = + - * / ), and after commas:
Examples:
var values = ["Volvo", "Saab", "Fiat"];
Code Indentation
Always use 4 spaces for indentation of code blocks:
Functions:
return (5 / 9) * (fahrenheit - 32);
}
![]() |
Do not use tabs (tabulators) for indentation. Different editors interpret tabs differently. |
---|
Statement Rules
General rules for simple statements:
- Always end a simple statement with a semicolon.
Examples:
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
General rules for complex (compound) statements:
- Put the opening bracket at the end of the first line.
- Use one space before the opening bracket.
- Put the closing bracket on a new line, without leading spaces.
- Do not end a complex statement with a semicolon.
Functions:
return (5 / 9) * (fahrenheit - 32);
}
Loops:
x += i;
}
Conditionals:
greeting = "Good day";
} else {
greeting = "Good evening";
}
Object Rules
General rules for object definitions:
- Place the opening bracket on the same line as the object name.
- Use colon plus one space between each property and its value.
- Use quotes around string values, not around numeric values.
- Do not add a comma after the last property-value pair.
- Place the closing bracket on a new line, without leading spaces.
- Always end an object definition with a semicolon.
Example
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Short objects can be written compressed, on one line, using spaces only between properties, like this:
line Length <80
For readability, avoid lines longer than 80 characters.
If a Javascript statement does not fit on one line, the best place to break it, is after an operator or a comma.
Example
"Hello Dolly.";
Naming Conventions
Always use the same naming convention for all your code. For example:
- Variable and function names written as camelCase
- Global variable written in UPPERCASE
- Constants (like PI) written in UPPERCASE
Should you use hyp-hens, camelCase, or under_scores in variable names?
this is a question programmers often discuss. The answer depends on who you ask:
Hyphens in HTML and CSS:
HTML5 attributes can start with data- (data-quantity, data-price).
CSS uses hyphens in property-names (font-size).
![]() |
Hyphens can be mistaken as subtraction attempts. Hyphens are not allowed in Javascript names. |
---|
Underscores:
Many programmers prefer to use underscores (date_of_birth), especially in SQL databases.
Underscores are often used in PHP documentation.
PascalCase:
PascalCase is often preferred by C programmers.
camelCase:
camelCase is used by Javascript itself, by jQuery, and other Javascript libraries.
![]() |
Do not start names with a $ sign! It will put you in conflict with many Javascript library names. |
---|
Loading Javascript in HTML
Use simple syntax for loading external scripts (the type attribute is not necessary):
Accessing HTML Elements
A consequence of using "untidy" HTML styles, might result in Javascript errors.
these two Javascript statements will produce different results:
var obj = getElementById("demo")
If possible, use the same naming convention (as Javascript) in HTML.
File Extensions
HTML files should have a .html extension (not .htm).
CSS files should have a .css extension.
Javascript files should have a .js extension.
Use Lower Case File Names
Most web servers, namely Apache and Unix, servers are case sensitive about file names:
london.jpg cannot be accessed as London.jpg.
Other web servers (Microsoft, IIS) are not case sensitive:
london.jpg can be accessed as London.jpg or london.jpg.
If you use a mix of upper and lower case, you have to be extremely consistent.
If you move from a case insensitive, to a case sensitive server, even small errors can break your web site.
To avoid these problems, always use lower case file names (if possible).
Performance
Coding conventions are not used by computers. Most rules have little impact on the execution of programs.
Indentation and extra spaces are not significant in small scripts.
For code in development, readability should be preferred. Larger production scripts should be minified.
JavaScript Regular Expressions
A regular expression is a sequence of characters that forms a search pattern.
The search pattern can be used for text search and text replace operations.
What Is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe what you are searching for.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text replace operations.
Syntax
Example
Example explained:
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
Using String Methods
In JavaScript, regular expressions are often used with the two string methods: search() and replace().
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.
Using String search() With a Regular Expression
Example
Use a regular expression to do a case-insensitive search for "w3schools" in a string:
var n = str.search(/w3schools/i);
The result in n will be:
Using String search() With String
The search method will also accept a string as search argument. The string argument will be converted to a regular expression:
Example
Use a string to do a search for "W3schools" in a string:
var n = str.search("W3Schools");
Use String replace() With a Regular Expression
Example
Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:
var res = str.replace(/microsoft/i, "W3Schools");
The result in res will be:
Using String replace() With a String
The replace() method will also accept a string as search argument:
var res = str.replace("Microsoft", "W3Schools");
Did You Notice?
![]() |
Regular expression arguments (instead of string arguments) can be used
in the methods above. Regular expressions can make your search much more powerful (case insensitive for example). |
---|
Regular Expression Modifiers
Modifiers can be used to perform case-insensitive more global searches:
Modifier | Description |
---|---|
i | Perform case-insensitive matching |
g | Perform a global match (find all matches rather than stopping after the first match) |
m | Perform multiline matching |
Regular Expression Patterns
Brackets are used to find a range of characters:
Expression | Description |
---|---|
[abc] | Find any of the characters between the brackets |
[0-9] | Find any of the digits between the brackets |
(x|y) | Find any of the alternatives separated with | |
Metacharacters are characters with a special meaning:
Metacharacter | Description |
---|---|
\d | Find a digit |
\s | Find a whitespace character |
\b | Find a match at the beginning or at the end of a word |
\uxxxx | Find the Unicode character specified by the hexadecimal number xxxx |
Quantifiers define quantities:
Quantifier | Description |
---|---|
n+ | Matches any string that contains at least one n |
n* | Matches any string that contains zero or more occurrences of n |
n? | Matches any string that contains zero or one occurrences of n |
Using the RegExp Object
In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.
Using test()
The test() method is a RegExp expression method.
It searches a string for a pattern, and returns true or false, depending on the result.
The following example searches a string for the character "e":
Example
patt.test("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be:
You don't have to put the regular expression in a variable first. The two lines above can be shortened to one:
Using exec()
The exec() method is a RegExp expression method.
It searches a string for a specified pattern, and returns the found text.
If no match is found, it returns null.
The following example searches a string for the character "e":
Example 1
Since there is an "e" in the string, the output of the code above will be:
Complete RegExp Reference
For a complete reference, go to the Complete JavaScript RegExp Reference page.
The reference contains descriptions and examples of all RegExp properties and methods.
HTML Audio/Video DOM Reference
HTML Audio and Video DOM Reference
The HTML5 DOM has methods, properties, and events for the <audio> and <video> elements.
These methods, properties, and events allow you to manipulate <audio> and < video> elements using JavaScript.
HTML Audio/Video Methods
Method | Description |
---|---|
addTextTrack() | Adds a new text track to the audio/video |
canPlayType() | Checks if the browser can play the specified audio/video type |
load() | Re-loads the audio/video element |
play() | Starts playing the audio/video |
pause() | Pauses the currently playing audio/video |
HTML Audio/Video Properties
Property | Description |
---|---|
audioTracks | Returns an AudioTrackList object representing available audio tracks |
autoplay | Sets or returns whether the audio/video should start playing as soon as it is loaded |
buffered | Returns a TimeRanges object representing the buffered parts of the audio/video |
controller | Returns the MediaController object representing the current media controller of the audio/video |
controls | Sets or returns whether the audio/video should display controls (like play/pause etc.) |
crossOrigin | Sets or returns the CORS settings of the audio/video |
currentSrc | Returns the URL of the current audio/video |
currentTime | Sets or returns the current playback position in the audio/video (in seconds) |
defaultMuted | Sets or returns whether the audio/video should be muted by default |
defaultPlaybackRate | Sets or returns the default speed of the audio/video playback |
duration | Returns the length of the current audio/video (in seconds) |
ended | Returns whether the playback of the audio/video has ended or not |
error | Returns a MediaError object representing the error state of the audio/video |
loop | Sets or returns whether the audio/video should start over again when finished |
mediaGroup | Sets or returns the group the audio/video belongs to (used to link multiple audio/video elements) |
muted | Sets or returns whether the audio/video is muted or not |
networkState | Returns the current network state of the audio/video |
paused | Returns whether the audio/video is paused or not |
playbackRate | Sets or returns the speed of the audio/video playback |
played | Returns a TimeRanges object representing the played parts of the audio/video |
preload | Sets or returns whether the audio/video should be loaded when the page loads |
readyState | Returns the current ready state of the audio/video |
seekable | Returns a TimeRanges object representing the seekable parts of the audio/video |
seeking | Returns whether the user is currently seeking in the audio/video |
src | Sets or returns the current source of the audio/video element |
startDate | Returns a Date object representing the current time offset |
textTracks | Returns a TextTrackList object representing the available text tracks |
videoTracks | Returns a VideoTrackList object representing the available video tracks |
volume | Sets or returns the volume of the audio/video |
HTML Audio/Video Events
Event | Description |
---|---|
abort | Fires when the loading of an audio/video is aborted |
canplay | Fires when the browser can start playing the audio/video |
canplaythrough | Fires when the browser can play through the audio/video without stopping for buffering |
durationchange | Fires when the duration of the audio/video is changed |
emptied | Fires when the current playlist is empty |
ended | Fires when the current playlist is ended |
error | Fires when an error occurred during the loading of an audio/video |
loadeddata | Fires when the browser has loaded the current frame of the audio/video |
loadedmetadata | Fires when the browser has loaded meta data for the audio/video |
loadstart | Fires when the browser starts looking for the audio/video |
pause | Fires when the audio/video has been paused |
play | Fires when the audio/video has been started or is no longer paused |
playing | Fires when the audio/video is playing after having been paused or stopped for buffering |
progress | Fires when the browser is downloading the audio/video |
ratechange | Fires when the playing speed of the audio/video is changed |
seeked | Fires when the user is finished moving/skipping to a new position in the audio/video |
seeking | Fires when the user starts moving/skipping to a new position in the audio/video |
stalled | Fires when the browser is trying to get media data, but data is not available |
suspend | Fires when the browser is intentionally not getting media data |
timeupdate | Fires when the current playback position has changed |
volumechange | Fires when the volume has been changed |
waiting | Fires when the video stops because it needs to buffer the next frame |