setAttribute, getAttribute and removeAttribute in javascript

access the attributes of controls/modify attributes/get, set and remove attributes


Category: Java Script Tags: HTML, Java Script


Java Script tutorial 16

        Today i am going to show you how to handle and access the attributes of controls using
javascript.

<head>
<title>Example</title>
<script type="text/javascript">
function change()
{
var pElement = document.getElementById("paragraph1");
pElement.setAttribute("align", "center");
alert(pElement.getAttribute("align"));
pElement.removeAttribute("align");
}
</script>
</head>
<body>
<p id="paragraph1">This is some text.</p>
<button onclick="change()" >Press and see</button>
</body>
</html>

        Here in above code we made a paragraph which id is paragraph1 and a button whose onclick
event bounded with a javascript function change(). Inside change we get the element by id the we
use setAttribute for set the align to center. Then we access the current attribute by getAttribute and
show this is in alert. Now we remove that attribute(align) by removeAttribute.
        By this the the paragraph's align first get change to center and then again goes to left because
of removing that attribute and by default the align attribute is left.


Like 0 People
Last modified on 29 August 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 165
Questions: 16
Given Best Solutions: 16 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x