Modifying the document

DOM modifications is the key to making pages dynamic. Using the methods described below, it is possible to construct new page elements and fill them on-the-fly.

Creating elements

There are following methods for creating new elements in DOM:

document.createElement(tag)
Creates a new DOM element of type node:

var div = document.createElement('div')
document.createTextNode(text)
Creates a new DOM element of type text:

var textElem = document.createTextNode('Robin was here')

The createElement is the most commonly used method, but createTextNode is also good. It creates a text node that can be appended to another element.

For an empty element, creating a text node and appending it works much faster than innerHTML in most modern browsers.

But innerHTML is simpler and supports nested tags, so they both find their place in the world.

 

Cloning

An element can also be cloned:

elem.cloneNode(true)
Clones an element deeply, with all descendants.
elem.cloneNode(false)
Clones an element only, with attributes, but without children.

 

<!DOCTYPE html>
<html>
<body>

<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
<ul id="myList2"><li>Water</li><li>Milk</li></ul>

<p id="demo">Click the button to copy an item from one list to another</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var itm=document.getElementById("myList2").lastChild;
var cln=itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
</script>

<p>Try changing the <em>deep</em> parameter to false, and only an empty LI element will be cloned.</p>
</body>
</html>

Adding elements

To do something with the element, you need to call the corresponding method of its parent:

parentElem.appendChild(elem)
Appends elem to the children of parentElem.The following example demonstrates creating and adding new element to BODY:

<div>…</div>
<script>
var div = document.body.children[0]

var span = document.createElement(‘span’)
span.innerHTML = ‘A new span!’
div.appendChild(span)
</script>

The new node becomes a last child of the parentElem.

 

parentElem.insertBefore(elem, nextSibling)
Inserts elem into the children of parentElem before the element nextSibling.The following example inserts a new node before the first child:

<div>

</div>
<script>
var div = document.body.children[0]

var span = document.createElement(‘span’)
span.innerHTML = ‘A new span!’
div.insertBefore(span, div.firstChild)
</script>

Note that you insertBefore with second argument null works as appendChild.

 

elem.insertBefore(newElem, null// same as
elem.appendChild(newElem)

 

All insertion methods return the inserted node.

Removing nodes

There are two main methods for removing nodes from DOM:

parentElem.removeChild(elem)
Remove the elem from the children of parentElem.
parentElem.replaceChild(elem, currentElem)
Replace the child element of parentElem, referenced by currentElem with the elem.

Both of them return a removed node which can later be reinserted into the DOM.

 

If you want to move an element, you don’t have to remove it first.

elem.appendChild/insertBefore remove elem from it’s previous place automatically.

The following example moves the last child to the top of children list:

<div>First div</div>
<div>Last div</div>
<script>
var first = document.body.children[0]
var last = document.body.children[1]

document.body.insertBefore(last, first)
</script>

The removal occurs automatically when insertion methods are called for a node which already has a parent.

 

Tasks and examples

Write a function which removes an element from DOM without referencing its parent.

The syntax should be: remove(elem)

 

<div>Very</div>
<div>Secret</div>
<div>Child</div>

<script>
var elem = document.body.children[0]

function remove(elem) { /* your code */
remove(elem) // <– should remove the element
</script>

Open solution

 

The parent of elem is referenced by the parentNode property.

And better don’t forget to return the removed element for compatibility.

So the code can be like this:

function remove(elem) {
  return elem.parentNode.removeChild(elem)
}

 

Write a function insertAfter(elem, refElem) to insert elem right after refElem.

<div>Very</div>
<div>Secret</div>

<script>
var elem = document.createElement(‘div’)
elem.innerHTML = ‘**Child**’

function insertAfter(elem, refElem) { /* your code */

insertAfter(elem, document.body.firstChild) // <— should work
insertAfter(elem, document.body.lastChild) // <— should work

</script>

Solution

To insert an element after refElem, we can insert it before refElem.nextSibling.

But what if there is no nextSibling? That means refElem is the last child of its parent, so we can just call appendChild.

The code:

function insertAfter(elem, refElem) {
var parent = refElem.parentNode
var next = refElem.nextSibling
if (next) {
return parent.insertBefore(elem, next)
} else {
return parent.appendChild(elem)
}
}

But the code could be much shorter if it used insertBefore null second argument feature:

function insertAfter(elem, refElem) {
    return elem.parentNode.insertBefore(elem, refElem.nextSibling)
}

If there is no nextSibling then the second argument of insertBefore becomes null and then insertBefore(elem,null) works as appendChild.

Write a function removeChildren to remove all children of an element.

<div>Very</div>
<div>Secret</div>
<div>Children</div>

<script>
function removeChildren(elem) { /* your code */

removeChildren(document.body) // makes BODY absolutely empty
</script>

Solution

First, let’s check a way how it shouldn’t be done

1 function removeChildren(elem) {
2   for(var k=0; k<elem.childNodes.length;k++) {
3     elem.removeChild(elem.childNodes[k])
4   }
5 }

If you check it in action – you’ll find that it doesn’t work.

That’s because childNodes always starts from 0, it autoshifts when first child is removed. But k increases +1 every iteration. So, k skips half of nodes.

The right solution:

1 function removeChildren(elem) {
2    while(elem.lastChild) {
3        elem.removeChild(elem.lastChild)
4    }
5 }

Another solution:

function removeChildren(elem) {
   elem.innerHTML = ''
}

 

 

Create an interface to generate the list.

For each item:

  1. Prompt the user for it’s contents.
  2. Create the item and append it to UL.
  3. The process ends when user presses ESC.

All elements must be created dynamically.

P.S. prompt returns null if user pressed ESC.

Solution

The solution is self-descriptive:

<!DOCTYPE HTML>

<html>
<body>
<h1>Creation of the list</h1>

<script>
var ul = document.createElement(‘ul’)
document.body.appendChild(ul)

while (true) {
var data = prompt(“Enter the contents for the item”, “”)

if (data === null) {
break
}

var li = document.createElement(‘li’)
li.appendChild(document.createTextNode(data))
ul.appendChild(li)
}
</script>

</body>
</html>

Note checking for null value as a loop-breaking condition. The prompt only returns it when ESC is pressed.

LI contents is populated by document.createTextNode to ensure proper work of <, > etc.

Summary

Creation methods:

  • document.createElement(tag) - creates a new element node.
  • document.createTextNode(value) - creates a new text node with given value
  • elem.cloneNode(deep) - clones the element

Inserting and removing methods are called from parent node. All of them return elem:

  • parent.appendChild(elem)
  • parent.insertBefore(elem, nextSibling)
  • parent.removeChild(elem)
  • parent.replaceChild(elem, currentElem)

Traversing the DOM

An access always starts from the document.

This object provides a variety of methods to search and modify elements.

The root: documentElement and body

The root is the DOM always document.documentElement. This special property will give access to the topmost HTML tag.

Another starting point can be the document.body, which represents the BODY tag.

documentElement

Both entry points are valid. But document.body can be null.

For example, you access document.body from an inline script in the HEAD, prepare to see null instead. That’s natural, because there is no BODY yet.

In the example below, first alert outputs null:

 

01 <!DOCTYPE HTML>
02 <html>
03     <head>
04         <script>
05             alert("Body from HEAD: "+document.body) // null
06         </script>
07     </head>
08     <body>
09         <div>The document</div>
10
11         <script>
12             // different browsers output different text here,
13             // because of different implementations of toString
14
15             alert("Body from inside body: " + document.body)
16         </script>
17     </body>
18 </html>

Open the code in new window

Contrary to this, document.documentElement is available always.

Also note that document.body can’t be undefinedIn the world of DOM, an “element not found” or “no such element” is always null.

 

As a more general rule than described above, it is impossible to reference elements that are not yet rendered at the time of script execution.

 

  • Write the code to access the UL using children.
  • Write the code to access the second LI using children.
Solution

The code is cross-browser:

document.body.children[1]
document.body.children[1].children[1]

It works fine, because there are no comment nodes before UL, so children indexes are same for IE<9 and other browsers.

 

Getting a list of children is not enough for convenient walking around elements.
So, there are additional properties for siblings, parent, etc.

The firstChild and the lastChild

The firstChild and lastChild properties allow to quickly access first or last child.

children

They are basically same as corresponding childNodes indexes:

1 var body = document.body
2
3 alert(body.firstChild === body.childNodes[0])
4 alert(body.lastChild === body.childNodes[body.childNodes.length-1])

 

parentNodepreviousSibling and nextSibling

  • The parentNode property references the parent node. It equals null fordocument.documentElement.
  • The previousSibling and nextSibling allow to access the left or the right neightbour.

For example:

01 <!DOCTYPE HTML>
02 <html>
03 <head>
04    <title>My page</title>
05 </head>
06 <body>
07     <div>The header</div>
08
09     <ul><li>A list</li></ul>
10
11     <div>The footer</div>
12 </body>
13
14 </body>
15 </html>

Picture for the document above (without whitespace nodes):

 

siblings

The browser always maintains correct helper links. It is possible to modify the DOM, add/remove elements, but no need to reassign the links manually, browser does that.

 

Write the code to check if the DOM Node elem is totally empty. That is, there are no children or text in it.

 

if (/*... put here your code to check if the elem is empty... */)

 

Open solution

Is it right that document.body.lastChild.nextSibling is always null?

.. Same question about document.body.children[0].previousSibling ?

Open solution

 

Summary

The DOM tree is tightly interlinked:

up
parentNode
down
children/childNodesfirstChildlastChild
left/right
previousSibling/nextSibling

Browser guarantees that the links are always correct. All of them are read-only.

If there is no such element (child, parent, neighbour etc), the value is null.

Child elements

There are several ways to obtain element children.

childNodes

An element keeps references to children in childNodes array-like property.

All nodes are referenced, including whitespace ones (excepts IE<9).

 

<!DOCTYPE HTML>
<html>
<body>
<div>Allowed readers:</div>
<ul>
<li>Bob</li>
<li>Alice</li>
</ul>

<!– a comment node –>

<script>
function go() {
var children = document.body.childNodes

for(var i=0; i<children.length; i++) {
alert(children[i])
}
}
</script>

<button onclick="go()" style="width:100px">Go!</button>

</body>
</html>

 

Sometimes we need to browse only element nodes, skipping text nodes. That’s what the children property is for.

It contains all element nodes. Check out the same example as above, but with children instead ofchildNodes.

It will output only element nodes as it should.

 

 

<!DOCTYPE HTML>
<html>
<body>
<div>Allowed readers:</div>
<ul>
<li>Bob</li>
<li>Alice</li>
</ul>

<!– a comment node –>

<script>
function go() {
var children = document.body.children

for(var i=0; i<children.length; i++) {
alert(children[i])
}
}
</script>

<button onclick="go()" style="width:100px">Go!</button>

</body>
</html>

Function arguments

In JavaScript, a function may be called with any number of arguments, no matter how many of them are listed.

For instance:

1 function go(a,b) {
2   alert("a="+a+", b="+b)
3 }
4
5 go(1)     // a=1, b=undefined
6 go(1,2)   // a=1, b=2
7 go(1,2,3) // a=1, b=2, extra argument is not listed

 

Arguments which are not provided become undefined. So we can see if the function is called with no arguments:

 

  function check(x) {
  alert(x === undefined) // ok now I know there is no x
}
4
5 check()

 

 

No syntax-level polymorphism

In some languages, a programmer may write two functions with same name but different parameter list, and the interpreter/compiler would choose the right one:

01 function log(a) {
02   ...
03 }
04
05 function log(a,b,c) {
06   ...
07 }
08
09 log(a) // first function is called
10 log(a,b,c) // second function is called

That is called function polymorphism. In JavaScript, there’s no such thing.

There can be only one function named log, which is called for any given arguments.

 

Accessing the unnamed arguments

How do we get more arguments than listed in parameters?

There is a special pseudo-array inside each function called arguments.

It contains all parameters by their number: arguments[0]arguments[1] etc.

Here is an example of how to list all arguments, no matter how many of them:

1 function sayHi() {
2   for(var i=0; i<arguments.length; i++) {
3     alert("Hi, " + arguments[i])
4   }
5 }
6  
7 sayHi("Cat""Alice")  // 'Hi, Cat', then 'Hi, Alice'

 

All parameters are in arguments, even if the function names some of them: sayHi(a,b,c).

The guts of arguments

A frequent beginner mistake is to use Array methods on it. Shortly, you can’t:

1 function sayHi() {
    var a = arguments.shift() 

// error! arguments is not Array

3   alert(a)
4 }
5
6 sayHi()

 

If it isn’t Array, then what it is? Let’s use the [[Class]] property to see it:

 

1 (function() {
2
3   alert( {}.toString.call(arguments) )  

// [object Arguments]

4
5 })()

 

This type is internally almost same as Object. It only looks like array, because it’s keys are numeric and it has length, but here the similarity ends.

Using arguments as Array

There is still a way to call array methods on arguments:

 

1 function sayHi() {
2   var args = [].join.call(arguments, ':')
3   alert(args)  // 1:2:3
4 }
5
6 sayHi(1,2,3)

 

Here we execute the join method of Array in the context of arguments, providing ':' as first argument.

It works, because internally most array methods (and join) use numeric indexes and length to work.

The join would work on a custom object as well, if the format is correct:

 

1 var obj = { 0: "A", 1: "B", length: 2 }
2
3 alert( [].join.call(obj) ) // "A,B"

 

Making a real Array

The arr.slice(start, end) copies the part of arr from start to end into the new array.

It can be called in the context of arguments to copy all elements into a real array:

  

1 function sayHi() {
2   var args = [].slice.call(arguments) 

// slice without parameters copies all

3
4   alert( args.join(':') ) // now .join works
5 }
6
7 sayHi(1,2)

 

 

The arguments and named parameters reference same values.

Updating arguments[..] causes the corresponding parameter to change and vice versa. For example:

 

1 f(1)
2
3 function f(x) {
4   arguments[0] = 5
5   alert(x) // 5, updating arguments changed x
6 }

 

And the reverse way:

 

1 f(1)
2
3 function f(x) {
4   x = 5
5   alert(arguments[0]) // 5, update of x reflected in arguments
6 }

 

Array methods which modify arguments also modify local parameters:

 

1 sayHi(1)
2
3 function sayHi(x) {
4   alert(x)           // 1
5   [].shift.call(arguments) 
6   alert(x)           // undefined, no x any more :/ 
7 }

 

Actually, the modern ECMA-262 5th specification splits arguments from local variables. But as of now, browsers still behave like described above. Try the examples to see.

Generally, it is a good practice not to modify arguments.

 

Default values

If you want a function parameter to be optional, there are two ways.

  1. First, you could check if for undefined and reassign:
    1 function sayHi(who) {
    2   if (who === undefined) who = 'me'
    3     
    4   alert(who) 
    5 }
  2. Or, use the OR || operator:
    1 function sayHi(who) {
    2   who = who || 'me'  // if who is falsy, returns 'me'
    3     
    4   alert(who) 
    5 }
    6 sayHi("John")
    7 sayHi()  // 'me'

    This way works great for parameters which are either not given or true. It happens most of time in real life.

 

A well-known function with variable number of arguments is Math.max. It returns the greatest or it’s arguments:

1 alert( Math.max(1, -2, 7, 3) )

 

Use func.apply(context, args) and Math.max to find the greatest element of an array:

 

var arr = [1, -2, 7, 3]
/* your code to output the greatest value of arr */

 

Solution

The solution:

1 var arr = [1, -2, 7, 3]
2
3 alert( Math.max.apply(Math, arr) ) // (*)

 

Here, we call Math.max, passing array of arguments args.

In the “natural” call Math.max(...), the context this is set to Math, the object before dot'.'. In our code we keep it same by explicitly passing to apply.

Actually, talking about Math.max - this method does not use the context at all. We could abuse that to simplify our code even further:

 

1 var arr = [1, -2, 7, 3]
2
3 alert( Math.max.apply(0, arr) ) // dummy '0' context

 

 

Keyword arguments

Imagine you’ve got a function with several arguments. And most of them will have default values.

Like the following:

1 function showWarning(width, height, title, contents, showYesNo) {
2   width = width || 200; // default values
3   height = height || 100;
4   
5   var title = title || "Warning";
6
7   ...
8 }

 

Here we have a function to show a warning window. It allows to specify width, height, title, textual contents and show the button if showYesNo is set.

Most parameters have default values.

Here is how we use it:

 

showWarning(nullnullnull"Warning text"true)
// or
showWarning(200, 300, null"Warning text")

 

The problem is: people tend to forget arguments order, and what they mean.

Imagine you have 10 arguments and most are optional. The function call becomes really terrifying.

In JavaScript, it is implemented with a parameters object:

 

1 function showWarning(options) {
2   var width = options.width || 200  // defaults
3   var height = options.height || 100
4   
5   var title = options.title || "Warning"
6
7   // ...
8 }

 

Calling such function is easy. You just pass an object of arguments like this:

1 showWarning({
2   contents: "Text",
3   showYesNo: true
4 })

 

Another bonus is that the arguments object can be reconfigured and reused:

 

01 var opts = {
02   width: 400,
03   height: 200,
04   contents: "Text",
05   showYesNo: true
06 }
07
08 showWarning(opts)
09
10 opts.contents = "Another text"
11 showWarning(opts) // another text with same options

 

Keyword arguments are employed in most frameworks.

Special arguments properties

arguments.callee

There is an interesting property of arguments, namely arguments.callee. It references the function which is being run.

This property is deprecated by ECMA-262 in favor of named function expressions and for better performance.

JavaScript implementations can optimize the code much better if they know that keeping arguments.callee is not required.

It will trigger error in “strict mode”, which you need to enable. Normally, it works.

 

Usually it is used for recursion in anonymous functions.

For example, setTimeout(func, ms) is a built-in function which calls func after ms microseconds.

1 setTimeout( 
2   function() { alert(1) }, // alerts 1 after 1000 ms (=1 second)
3   1000
4 )

 

The function has no name. To call it recursively 3 times, let’s use arguments.callee:

1 var i = 1
2     setTimeout( 
3     function() {
4 alert(i)
5     if (i++<3) setTimeout(arguments.callee, 1000)
6   },
7   1000
8 )

 

Another example is factorial:

1 // factorial(n) = n*factorial(n-1)
2 var func = function(n) { 
3   return n==1 ? 1 : n*arguments.callee(n-1) 
4 }

The factorial function given above works even if func is reassigned to something else. That’s because it uses arguments.callee to reference itself.

 

arguments.callee.caller

The property arguments.callee.caller keeps the reference to a calling function.

This property is deprecated by ECMA-262, for the same reason as arguments.caller.

There is a property arguments.caller with same meaning, but less supported. Don’t use it, stick to arguments.callee.caller, all browsers have it.

 

In the example below, arguments.callee.caller references the calling function of g, that is f.

01 f()
02
03 function f() {
04   alert(arguments.callee.caller) // undefined
05   g()
06 }
07
08 function g() {
09   alert(arguments.callee.caller) // f
10 }

Javascript Object Hierarchy

When you load a document in Navigator, it creates a number of JavaScript objects with property values based on the HTML in the document and other pertinent information. These objects exist in a hierarchy that reflects the structure of the HTML page itself. The following figure illustrates this object hierarchy.

Javascript Object Hierarchy

WINDOW OBJECTS WINDOW.DOCUMENT OBJECTS

  • window
  • window.frame
  • window.location
  • window.history
  • window.document
  • window.document.layer
  • window.document.link
  • window.document.image
  • window.document.area
  • window.document.anchor
  • window.document.applet
  • window.documentframe.form

WINDOW.DOCUMENT.FORM OBJECTS

  • window.document.form
  • window.document.form.textarea
  • window.document.form.text
  • window.document.form.fileupload
  • window.document.form.password
  • window.document.form.hidden
  • window.document.form.submit
  • window.document.form.reset
  • window.document.form.radio
  • window.document.form.checkbox
  • window.document.form.button
  • window.document.form.select
  • window.document.form.select.option

POP UP BOXES

ALERT BOX

The syntax for an alert box is: alert("yourtext");

The user will need to click “OK” to proceed.

Typical use is when you want to make sure information comes through to the user.

Examples could be warnings of any kind.
(Technical matters like “This site requires Flash plug-in”).

CONFIRM BOX:

The syntax for a confirm box is: confirm(“yourtext”);

The user needs to click either “OK” or “Cancel” to proceed.

Typical use is when you want the user to verify or accept something.

Examples could be age verification like “Confirm that you are at least 57 years old” or technical matters like “Do you have a plug-in for Shockwave Flash?”

- If the user clicks “OK”, the box returns the value true.
- If the user clicks “Cancel”, the box returns the value false.

if (confirm("Do you agree")) {alert("You agree")}
else{alert ("You do not agree")};

PROMPT BOX:

The prompt box syntax is: prompt(“yourtext”,”defaultvalue”);

The user must click either “OK” or “Cancel” to proceed after entering the text.

Typical use is when the user should input a value before entering the page.

Examples could be entering user’s name to be stored in a cookie or entering a password or code of some kind.

- If the user clicks “OK” the prompt box returns the entry.
- If the user clicks “Cancel” the prompt box returns null.

Since you usually want to use the input from the prompt box for some purpose it is normal to store the input in a variable, as shown in this example:

username=prompt("Please enter your name","Enter your name here");

Script tag and Html Attributes:

The <script> Tag :

The script tag has two purposes:
1. It identifies a block of script in the page.
2. It loads a script file.
What it does depends on the presence of src attribute.
src=”url”
The src attribute is optional. If it is present, then its value is a url which identifies a .js file. The loading and processing of the page pauses while the browser fetches, compiles, and executes the file. The content between the <script src=”url”> and the </script> should be blank.
If the src attribute is not present, then the content text between the <script> and the </script> is compiled and executed. In older versions of HTML it was necessary to specify a value for “type”. The scripting language is specified by the “type” attribute.
<script type=”text/javascript”>
// JavaScript code here
</script>
However in HTML5, “type” defaults to “text/javascript”. Therefore, HTML5 <script> tags can be shortened in the following fashion.
<script>
// JavaScript code here
</script>
By default script tag is for client side if we want it to run on server side we have to add attribute which tells it runs on server side.
The document.write method provides a way of incorporating strings into the HTML content of the page.This simply prints the specified text to the page.
<script>
document.write(‘*Hello, there!*’)
</script>

Changing HTML Content:

<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>
<p id=”demo”>
JavaScript can change the content of an HTML element.
</p>
<script>
function myFunction()
{
x=document.getElementById(“demo”); // Find the element
x.innerHTML=”Hello JavaScript!”; // Change the content
}
</script>
<button type=”button” onclick=”myFunction()”>Click Me!</button>
</body>
</html>
In this example we have assigned id to paragraph element which is demo. In the script tag we can also define funtions by using function keyword which is followed by the name of funtion myFunction in this case. The getElementById funtion returns html element having demo as id so in this case it returns paragraph element. The innerHTML funtion is used to change content of paragraph element.
Button tag <button> is used for buttons. Its onclick event is assigned funtion myFunction so whenever the button is clicked it calls the funtion.

Html Attributes:

The rel attribute is used to provide information about the relationship between the document that’s being linked to (as defined in the href attribute) and the referencing document.One of the most common uses of the rel attribute, in the context of the a element, is to specify a value of “nofollow”. This is to indicate to search engines that the linked document should not be indexed by the search engine, and that any reputation/value associated with the linking site is not passed on such that it benefits the linked page in search results.
The href attribute defines the document to which the link leads. This may be a web page in the same directory, a page somewhere else on the same server, a location within the current page, or a web page—or any another kind of document—stored on another server.

JavaScript is a Scripting Language

A scripting language is a lightweight programming language. JavaScript is programming code that can be inserted into HTML pages. JavaScript inserted into HTML pages, can be executed by all modern web browsers.

<!DOCTYPE html>
<html>
<body>
<p>
JavaScript can write directly into the HTML output stream:
</p>
<script>
document.write(“<h1>This is a heading</h1>”);
document.write(“<p>This is a paragraph.</p>”);
</script>
<p>
You can only use <strong>document.write</strong> in the HTML output.
If you use it after the document has loaded (e.g. in a function), the whole document will be overwritten.
</p>
</body>
</html>

Changing HTML Content:

<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>
<p id=”demo”>
JavaScript can change the content of an HTML element.
</p>
<script>
function myFunction()
{
x=document.getElementById(“demo”); // Find the element
x.innerHTML=”Hello JavaScript!”; // Change the content
}
</script>
<button type=”button” onclick=”myFunction()”>Click Me!</button>
</body>
</html>

Changing HTML Styles:

<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>
<p id=”demo”>
JavaScript can change the style of an HTML element.
</p>
<script>
function myFunction()
{
x=document.getElementById(“demo”) // Find the element
x.style.color=”#ff0000″; // Change the style
}
</script>
<button type=”button” onclick=”myFunction()”>Click Me!</button>
</body>
</html>