Reputation: 105
Its very strange condition for me but anchors.length only give total number of anchors when i place script after all anchors tag and when i place before all anchors it gives zero....so i did this but now function lngt() is not returning length of anchors please help me i just stuck..
here is my code
<div class="box">
<script>
var na;
na = lngt();
for(i = 0 ; i < na ; i++)
{
txt = document.anchors[i].innerHTML;
lnk = document.anchors[i].name;
document.write( "<a href='#"+lnk+"'>"+ txt + "</a></br>");
}
</script>
</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br /><br/><br/><br/>
<a name="a">anchor 1</a><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br
/><br/><br/><br/>
<a name="b">anchor 2</a><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br
/><br/><br/><br/>
<a name="c">anchor 3</a><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br
/><br/><br/><br/>
<a name="d">anchor 4</a><br/>
<script>
function lngt(){
var nc = document.anchors.length;
return nc;
}
</script>
When i put both script at the end its working fine :/ Thanks in Advance :)
Upvotes: 1
Views: 283
Reputation:
window.onload
, or add the script
tag after your HTML elements).innerHTML
to put new elements in your page.<script>
window.onload = function () {
var anchors = document.anchors;
var toc = document.getElementById('toc');
for (var i = 0, l = anchors.length; i < l; i++) {
toc.innerHTML += '<div><a href="#' + anchors[i].name + '">' + anchors[i].innerHTML +'</a></div>';
}
};
</script>
<div id="toc"></div>
<a name="a">anchor 1</a>
<a name="b">anchor 2</a>
<a name="c">anchor 3</a>
<a name="d">anchor 4</a>
Upvotes: 2
Reputation: 887423
You're calling the function (in the upper <script>
block) before the elements exist.
Upvotes: 0