0

I have a Javascript question that I am curious about. When using:

var test = document.links(arrayNum).name;

Is it possible to dig deeper into specifying links? For instance, if there is just a group of links from within a div with an id that you would like to target as opposed to all the links on the page could you write something like:

var test = document.getElementById('divId').links(arrayNum).name;

Or could I add a class to the statement to target only the links associated with it?

var test = document.links.className(arrayNum).name;

Is anything like this feasible?

Slevin
  • 312
  • 2
  • 12
  • 3
    Why don't you tried those things by your self... if it does not work, then you can ask question about it. – Cristian May 07 '10 at 13:01
  • 1
    I have tried them by myself and they didn't work, hence my asking a question about it. When it didn't work, that meant my syntax was wrong so I came here, showed what I had tried and hoped somebody could elaborate. Correct me if I'm wrong but that seems to be the premise of this site. – Slevin May 07 '10 at 14:49

2 Answers2

1

document.links is purely document-wide, but there are other DOM methods you can use, eg.:

var test= document.getElementById('divId').getElementsByTagName('a')[n].name;

and:

var test= document.getElementsByClassName('someclass').name;

(that one is quite new and not supported by all browsers, so if you want it to work everywhere you'll have to add fallback, and be careful for the difference between live and non-live node lists.)

(Note [] array index syntax not (). And incidentally, why name? Typically you'd avoid <a name> today in favour of general-purpose id today.)

Community
  • 1
  • 1
bobince
  • 528,062
  • 107
  • 651
  • 834
0

The links collection belongs to the document object only, it is not on the prototype chain for elements. It's not quite the same thing, but you can get all the <a> tags of a particular element using getElementsByTagName:

// retrieve a collection of all a elements
var test = document.getElementById('divId').getElementsByTagName("a");

In browsers that support it, you can use querySelectorAll:

// retrieve a collection of all links
var test = document.getElementById('divId').querySelectorAll("a, area");

Or you could use a library like jQuery or mootools to do all the hard work for you:

var test = $("#divId a, #divId area");
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • Thank you for the break down of this. I am new to JQuery and didn't think of that as an option. But this is definitely something I'll be using the future. – Slevin May 07 '10 at 14:47
  • @Slevin: Don't forget to take a look at bobince's answer. He offers some sound advice on the use of the `name` attribute. – Andy E May 07 '10 at 22:49