Coder
Coder

Reputation: 169

Get the exact position of div using div class

How can i get the top.left, right and width of the div which has no id but only class is defined.

<div class="content">
</div> 

I want to get the exact position on the screen using content class. is it possible using jqyery??

Iframe

Alert code

Upvotes: 0

Views: 129

Answers (1)

Weafs.py
Weafs.py

Reputation: 22992

You can use getBoundingClientRect() for top, left and right values. For width you could use offsetWidth if the width isn't defined anywhere.

If the width is defined inline you could use element.style.width, if it is defined in stylesheet you could use getComputedStyle(element).

If you want to get the values for all elements with class content, you'll have to loop through them individually; else just remove the for loop and put 0 instead of i.

var content = document.getElementsByClassName('content');

for (i = 0; i < content.length; i++) {
  console.log(content[i].getBoundingClientRect().top) //top
  console.log(content[i].getBoundingClientRect().left) //left
  console.log(content[i].getBoundingClientRect().right) //right
  console.log(content[i].offsetWidth); //width
}

Example:

 var content = document.getElementsByClassName('content')[0];

 console.log(content.getBoundingClientRect().top) //top
 console.log(content.getBoundingClientRect().left) //left
 console.log(content.getBoundingClientRect().right) //right
 console.log(content.offsetWidth); //width
<div class="content"></div>

Upvotes: 1

Related Questions