Changing Elements

To get an attribute of an element the .getAttribute(); method can be used:

 

myElement.getAttribute("color"); //passing in the desired property to get within quotes

 

Similarly, to set an attribute for an element the .setAttribute(); can be used:

 

myElement.setAttribute("color", "red"); //passing in the desired property followed by the value to set within quotes

 

*note: if an attribute doesn't already exist for that element, it will be created

 

We've also already seen that the .innerHTML method can be used to change the text within an element.

 

 

An alternative approach could use the style method:

 

document.getElementBtId("myElement").style.color = "#0000FF" ;

 

Which is equivalent to:

 

var myElement = document.getElementBtId("myElement") ;

var myElementSytle = myElement.style ;

 

So now, myElementStyle can be directly used to set the css styling for the specified element:

 

myElementStyle.margin = "5px 0 10px 7px" ;

myElementStyle.color = "blue" ;

myElementStyle.border = "solid 2px red" ;

myElementStyle.paddingBottom = "2em" ;

 

*note: the use of camelCase instead of a hypen as in normal css being padding-bottom, we use paddingBottom

 

Since an element's properties can be accessed as though in an array, we can take this further and create a function that would work upon a passed in element and it's desired property and value to change:

Save & refresh browser:

Here's my heading

Using JavaScript to change the properties of an element!

 

Perhaps the above style changing function isn't the most useful of functions since it's probably easier to simply write:

myElement.style.textDecoration = "underline";

but this approach shows another way of changing an element.

Leave a Reply