Creating and Accessing HTML Elements
using JavaScript
[this page | pdf | back links]
More
advanced webpages typically use JavaScript
to manipulate individual HTML elements
on a webpage. For example, HTML <a> (i.e. anchor)
elements can be created or accessed using JavaScript as follows:
Create:
|
e.g. var x = document.createElement("A")
|
Access:
|
e.g. var x = document.getElementById(ElementId)
|
Here
the ElementId is the id attribute of the
element. The A is the JavaScript
DOM name for an anchor element. Occasionally the most natural way to access an
element does not involve its id attribute in which case there are other
possible approach, see detail on individual elements.
For some types of
elements (e.g. because there will only typically be one of them in any given
document, or because they can be accessed via a specific document property)
there may be other simpler ways of accessing the element. For example. the
following elements might more commonly be accessed as follows:
Element
|
Alternative ways of
accessing them through JavaScript, e.g.
|
<body>
|
var x = document.getElementsByTagName("BODY")[0]
or
var x = document.body
|
<head>
|
var x = document.getElementsByTagName("HEAD")[0]
|
<html>
|
var x = document.getElementsByTagName("HTML")[0]
or
var x = document.documentElement
|
<iframe>
|
var x = window.frames[x]
|
<title>
|
var x = document.getElementsByTagName("TITLE")[0]
|
Some types of element
come in various types, and it is also in practice necessary to set their type
when they are created, e.g.:
Element
|
Steps to create
relevant element type
|
<input>
|
e.g. var x = document.createElement("INPUT")
then the type of <input> element needs to be
set, e.g.:
x.setAttribute("type", ElementType)
where ElementType
is e.g. button or checkbox, …
|
To add elements that
don’t reside within any single element inside the document body (such a <datalist>
element, you should first create it and then add it to the document.body object.
JavaScript DOM object names
corresponding to different HTML elements supported by HTML 5 include:
NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)