Javascript Reference - HTML DOM Button name Property








The name property sets or gets the value of the name attribute of a button.

Browser Support

name Yes Yes Yes Yes Yes

Syntax

Return the name property:

var v = buttonObject.name

Set the name property:

buttonObject.name=name

Property Values

Value Description
name Set the name of the button




Return Value

A String representing the name of the button.

Example

The following code shows how to get the value of the name attribute of a button.


<!DOCTYPE html>
<html>
<body>
<button id="myBtn" name="myname" onclick="myFunction()">test</button>
<p id="demo"></p>
<!--  w  w  w  .  j a v a2 s .c om-->
<script>
function myFunction() {
    var x = document.getElementById("myBtn").name;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to change the value of the name attribute of a button.


<!DOCTYPE html>
<html>
<body>
<button id="myBtn" name="myname">My Button</button>
<button onclick="display()">Display</button>
<button onclick="change()">Change</button>
<!-- w  w w.  j a v  a  2 s  .c  o m-->
<script>
function display() {
    var x = document.getElementById("myBtn").name;
    console.log(x);
}

function change() {
    var x = document.getElementById("myBtn").name = "newButtonName";
    console.log (x);
}
</script>

</body>
</html>

The code above is rendered as follows: