Chapter 10. JavaScript in the DOM

10.1 Inserting and Executing JavaScript Overview

JavaScript can be inserted into an HTML document by including external JavaScript files or writing page-level inline JavaScript, which is basically the contents of an external JavaScript file literally embedded in the HTML page as a text node. Don’t confuse element inline JavaScript contained in attribute event handlers (i.e., <div onclick="alert('yo')"></div>) with page inline JavaScript (i.e., <script>alert('hi')</script>).

Both methods of inserting JavaScript into an HTML document require the use of a <script> element node. The <script> element can contain JavaScript code or can be used to link to external JavaScript files via the src attribute. Both methods are explored in the following code example.

Live code

<!DOCTYPE html>
<html lang="en">

<!-- external, cross domain JavaScript include -->
<script src=""></script>

<!-- page inline JavaScript -->



It’s possible to insert and execute JavaScript in the DOM by placing the JavaScript in an element attribute event handler (i.e., <div onclick="alert('yo')"></div>) and using the javascript: protocol (e.g., <a href="javascript:alert('yo')"></a>), but this is no longer considered a modern practice.

Trying to include an external JavaScript file and writing page inline JavaScript using the same <script> element will result ...

Get DOM Enlightenment now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.