Last modified on 12 June 2013, at 16:04

JavaScript/Changing Elements

Previous: Adding Elements Index Next: Changing Element Styles

In JavaScript you can change elements by using the following syntax:

element.attribute="new value"

Here, the "src" attribute of an image is changed so when the script is called, it changes the picture from "myPicture.jpg" to "otherPicture.jpg".

//The Html
<img id="example" src="myPicture.jpg">
//The JavaScript
document.getElementById("example").src="otherPicture.jpg";

In order to change an element, you use its argument name for the value you wish to change. For example, let's say we have a button, and we wish to change its value.

<input type="button" id="myButton" value="I'm a button!">

Later on in the page, with JavaScript, we could do the following to change that button's value:

myButton = document.getElementById("myButton"); //searches for and detects the input element from the 'myButton' id
myButton.value = "I'm a changed button"; //changes the value

To change the type of input it is (button to text, for example) then use:

myButton.type = "text"; //changes the input type from 'button' to 'text'.

Another way to change or create an attribute is to use a method like element.setAttribute("attribute","value") or element.createAttribute("attribute","value"). Use "setAttribute()" to change a attribute that has been defined before.

//The Html
<div id="div2"></div> //Make a div with an id of div2 (we also could have made it with JavaScript)
//The Javascript
var e = document.getElementById("div2"); //Get the element
e.setAttribute("id","div3"); //Change id to div3

But use "createAttribute()" if you want to set a value that hasn't been defined before.

var e = document.createElement('div'); //Make a div element (we also could have made it with Html)
e.createAttribute("id","myDiv"); //Set the id to "myDiv"
Previous: Adding Elements Index Next: Changing Element Styles