views:

37

answers:

1

I'd like to get the titles of some links on a webpage to show them in a table. The page links change a lot, so I don't know how to make the table "dynamic", to show the link titles correctly.

Is this possible with JavaScript?

+2  A: 

assuming an html like the following

  <div id="toc"></div>

  <a href="1" title="title of a1 link">a1</a> blah blah<br>
  <a href="2" title="title of a2 link">a2</a> blah blah<br>
  <a href="3" title="title of a3 link">a3</a> blah blah<br>

the following javascript would do what you want..

var links = document.getElementsByTagName('a'); // get all links
var toc = document.getElementById('toc'); // get the (table of contents) element where the titles will be inserted

for (var i = 0 ; i < links.length; i++)
{
  // for each link create a div
  newTitle = document.createElement('div');
  // which will hold the title of the link
  newTitle.innerHTML = links[i].title;

  // and then append it to the table of contents element..
  toc.appendChild( newTitle );
}
Gaby
Thanks a lot! and what if I wanted to do this from a remote html page?
carnegie
@carnegie You will need to use a server-side proxy to access the html from the remove domain (why : http://stackoverflow.com/questions/1201429/jquery-ajax-fails-when-url-is-from-different-server ). Then you would need to use Ajax to call the proxy through javascript and then access the results in a similar fashion as the code above ..
Gaby