HOLLA TECH - LEARN

Changing Attributes
 

Once you have selected the element(s) you want to work with, you can change their attributes.
As we have seen in the previous lessons, we can change the text content of an element using the innerHTML property.
Similarly, we can change the attributes of elements.
For example, we can change the src attribute of an image: 

<img id=“myimg” src=“orange.png” alt=“” />
<script>
var el = document.getElementById(“myimg”);
el.src = “apple.png”;
</script> 

 

We can change the href attribute of a link:

<a href=“http://www.example.com”>Some link</a>
<script>
var el = document.getElementsByTagName(“a”);
el[0].href = “http://www.sololearn.com”;
</script> 

 

NOTE!
Practically all attributes of an element can be changed using JavaScript.

Changing Style
 

The style of HTML elements can also be changed using JavaScript.
All style attributes can be accessed using the style object of the element.
For example:

<div id=“demo” style=width:200px>some text</div>
<script>
  var x = document.getElementById(“demo”);
  x.style.color = “6600FF”;
  x.style.width = “100px”;
</script> 

 

The code above changes the text color and width of the div element.  

NOTE!
All CSS properties can be set and modified using JavaScript. Just remember, that you cannot use dashes (-) in the property names: these are replaced with camelCase versions, where the compound words begin with a capital letter. For example: the background-color property should be referred to as backgroundColor.

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE JAVASCRIPT MAIN COURSE PAGE. 

JAVASCRIPT MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT