Consider there is a DIV on a blank browser page at coordinate (2,2) in pixels and a button.If i click on the button it must send the coordinates (2,2) to function which will DETECT what is at (2,2) whether it is a DIV , a BUTTON , etc and also return its ID.
Here is what i tried :
<!DOCTYPE html>
<html lang="en">
<head>
<title>elementFromPoint example</title>
<script>
function changeColor(newColor) {
//To get element from coordinate 2,2
var elem = document.elementFromPoint(2, 2);
//Here i wanted to print what i am getting in var elem
document.getElementById("status").innerHTML = elem;
//next line changes color whatever is at 2,2
elem.style.color = newColor;
//But i want to know whats at 2,2 or get its ID or class.
}
</script>
</head>
<body>
<p id="para1">Some text here</p> <button onclick="changeColor('blue');">blue</button> <span id="status"></span> </body>
</html>
But by this method i am only able to change its color, but i am stuck on how can i get its ID or TYPE (div/ button / para / etc).
var elem = document.elementFromPoint(2, 2);
gives you the element reference and id
is a property of that element
Try
console.log(elem.id);
for type
console.log(elem.tagName);
To update your status something like:
document.getElementById("status").innerHTML = 'ID:' +elem.id +' , Tag:' +elem.tagName;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.