...

View Full Version : How Show html element id with javaScript?



Farshad
10-02-2012, 10:43 AM
HI dears
i have a div that contain several <a> tags.
i write a function on script in head
i want when click on evry <a> tag this function execute and alert this <a> id attribute

my code is:



<script type="text/javascript">
function IDvalue(obj) {
var x= document.getElementsByName(obj).id;
alert(x);
}
</script>








<div class="DIV_2">
<a href="#1" id="1" onclick="IDvalue(this)">1</a>
<a href="#2" id="2" onclick="IDvalue(this)">2</a>
<a href="#3" id="3" onclick="IDvalue(this)">3</a>
<a href="#4" id="4" onclick="IDvalue(this)">4</a>
<a href="#5" id="5" onclick="IDvalue(this)">5</a>
<a href="#6" id="6" onclick="IDvalue(this)">6</a>
<a href="#7" id="7" onclick="IDvalue(this)">7</a>
<a href="#8" id="8" onclick="IDvalue(this)">8</a>
<a href="#9" id="9" onclick="IDvalue(this)">9</a>

</div>

vwphillips
10-02-2012, 11:04 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
<script type="text/javascript">
function IDvalue(obj) {
alert(obj.id); // you are passing an object not a string
}
</script>
</head>

<body>
ID names muststart with a letter or $
<div class="DIV_2">
<a href="#1" id="a1" onclick="IDvalue(this)">1</a>
<a href="#2" id="a2" onclick="IDvalue(this)">2</a>
<a href="#3" id="a3" onclick="IDvalue(this)">3</a>
<a href="#4" id="a4" onclick="IDvalue(this)">4</a>
<a href="#5" id="a5" onclick="IDvalue(this)">5</a>
<a href="#6" id="a6" onclick="IDvalue(this)">6</a>
<a href="#7" id="a7" onclick="IDvalue(this)">7</a>
<a href="#8" id="a8" onclick="IDvalue(this)">8</a>
<a href="#9" id="a9" onclick="IDvalue(this)">9</a>

</div>
</body>

</html>

mrhoo
10-02-2012, 04:26 PM
You can also 'delegate' any event that bubbles to a parent element, and handle it from there.


<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Alert id</title>
<script>
document.onclick=function(e){
e=e && e.target || window.event && event.srcElement;
if(e.tagName=='A' && e.id) alert(e.id);
}
</script>
</head>

<body>
ID names muststart with a letter or $
<div class="DIV_2">
<a href="#1" id="a1">1</a>
<a href="#2" id="a2">2</a>
<a href="#3" id="a3">3</a>
<a href="#4" id="a4">4</a>
<a href="#5" id="a5">5</a>
<a href="#6" id="a6">6</a>
<a href="#7" id="a7">7</a>
<a href="#8" id="a8">8</a>
<a href="#9" id="a9">9</a>
</div>

</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum