HTML DOM clientTop Property


The HTML DOM clientTop property returns the width of the top border of an element in pixels. It is a read-only property. Top margin or top padding of an element are not included by this property.

Syntax

Following is the syntax for clientTop property −

element.clientTop;

Example

Let us see an example of the clientTop property −

<!DOCTYPE html>
<html>
<head>
<style>
#styleDiv {
   height: 250px;
   font-size:35px;
   text-align:center;
   width: 400px;
   padding: 10px;
   margin: 15px;
   border-top: 15px solid blue;
   background-color: lightgreen;
}
</style>
</head>
<body>
<p>Click the below button to get the div top border width in pixels </p>
<button onclick="topWidth()">TOP WIDTH</button>
<div id="styleDiv">
<b>A sample div</b>
</div>
<p id="Sample"></p>
<script>
   function topWidth() {
      var x = document.getElementById("styleDiv");
      var txt = "Border top width: " + x.clientTop + "px";
      document.getElementById("Sample").innerHTML = txt;
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking TOP WIDTH −

In the above example −

We have created a div with id “styleDIV” and have a style applied to it using its id.

#styleDiv {
   height: 250px;
   font-size:35px;
   text-align:center;
   width: 400px;
   padding: 10px;
   margin: 15px;
   border-top: 15px solid blue;
   background-color: lightgreen;
}

The div −

<div id="styleDiv">
<b>A sample div</b>
</div>

We have then created a button TOP WIDTH that will execute the topWidth() method on click −

<button>TOP WIDTH</button>

The topWidth() gets the <div> element using the getElementById() method and assigns it to variable x. Then using the clientTop property on the <div> we get its top border width in pixels and after appending some text assigns it to variable txt. The text inside txt is then displayed inside the paragraph with id “Sample” using the innerHTML property and assigning the txt variable to it −

function topWidth() {
   var x = document.getElementById("styleDiv");
   var txt = "Border top width: " + x.clientTop + "px";
   document.getElementById("Sample").innerHTML = txt;
}
raja
Published on 07-Aug-2019 13:28:56
Advertisements