getAttribute isn't working
I have this
<body>
<div id=myid0 i='Keliot'> 0</div>
<div id=myid1 i='Ukonh'> 1</div>
<div id=myid2 i='plotis'> 2</div>
</body>
I am trying to get the value of i
but I am getting null for myid0
. this is what I am using
alert(document.getElementById('myid0').getAttribute('i'));
error is
Erro开发者_JAVA百科r: 'document.getElementById(...)' is null or not an object
Make sure you place the code after the elements you're selecting so they exist when you try to select them.
Example: http://jsfiddle.net/dS4t5/
<body>
<div id=myid0 i='Keliot'> 0</div>
<div id=myid1 i='Ukonh'> 1</div>
<div id=myid2 i='plotis'> 2</div>
<!-- script is placed here, after the elements have loaded -->
<script type="text/javascript">
alert(document.getElementById('myid0').getAttribute('i'));
</script>
</body>
As noted by @typo.pl, this is only one way to make sure the DOM elements exist.
You can place the code in a function, and call it from body onload="myfunc();"
, or from window.onload = myfunc;
. Or you could use a less precise method of setting a timer with setTimeout
to execute the code.
Put quotes around your id attributes:
<body>
<div id='myid0'>0</div>
<div id='myid1'>1</div>
<div id='myid2'>2</div>
</body>
Also, I would advise against creating custom element attributes. i is not a standard xHTML element attribute.
精彩评论