PDA

View Full Version : Help for building links from named anchors!



sergiozambrano
06-19-2009, 05:48 PM
Hi guys

I'm an old designer but not better at JavaScript than copy/paste and I haven't found enough examples to make this happen.

I need a JavaScript to get all the named anchors in the page and generate a paragraph (or div, or ul list) with all the links corresponding to the found named anchors.

I can edit the code myself to add them different ID numbers or name them as the anchor was.

Thank you very much!.

Jesdisciple
06-19-2009, 07:25 PM
Is there any chance you'd be interested in going beyond your current JavaScript knowledge? And how do you feel about wikis? I administrate an (incomplete) JavaScript wiki which aims to reference the documentation and standards where applicable. If you're interested, I'd be glad to give a link. (I do want to know whether you're open to learning regardless of your opinion on wikis.)

This is untested.
function listLinks(name, tag){
if(typeof tag == 'undefined')
tag = 'ul';
var elements = document.getElementsByName(name);
var list = document.createElement(tag);
for(var i = 0; i < elements.length; i++){
var element = elements[i];
if(element.tagName.toLowerCase() == 'a'){
var item = document.createElement('li');
var clone = element.cloneNode(true);
clone.removeAttribute('id'); // Preserve the original's "first" status.
item.appendChild(clone);
list.appendChild(item);
}
}
return list;
}

clueful
06-20-2009, 03:07 AM
I need a JavaScript to get all the named anchors in the page and generate a paragraph (or div, or ul list) with all the links corresponding to the found named anchors.

Insert this anywhere below the last anchor and below a div with id 'linkDiv', which will contain the list:
<script type='text/javascript'>

(function linkTableFromAnchors( tableParentId )
{
var allAnchors = document.getElementsByTagName( 'a' ),
parentElem = document.getElementById( tableParentId ),
list = document.createElement( 'ul' ),
listItem, lnk, tableLink, linkText;

for( var i = 0, len = allAnchors.length; i < len; i++ )
if( !(lnk = allAnchors[ i ]).href && ( linkText = lnk.name || lnk.id ) )
{
tableLink = document.createElement('a');
tableLink.href = '#' + linkText;
tableLink.appendChild( document.createTextNode( linkText ));
( listItem = document.createElement( 'li' ) ).appendChild( tableLink );
list.appendChild( listItem );
}

parentElem.appendChild( list );

})( 'linkDiv' );

</script>