la***********@zipmail.com wrote:
Hi,
How would I use Javascript to get the value of a hyperlink. That is,
what function could I substitute below to get the value "2"?
<a href="javascript:alert( /* WHat goes here? */ );">2</a>
Using the javascript pseudo protocol as the value of an href attribute
is not a good idea, use a real URL and onclick. If you really don't
want the href to do anything, then don't use an A element, use a span or
div styled to look like a link.
If there is no HTML inside the A element, then:
<a href="#" onclick="alert(this.firstChild.data);">2</a>
If the A element will contain HTML, say <b> or <i> elements, you may
want to use IE's innerText and the W3C textContent properties of the A
element (will IE 7 support textContent?). A cross-browser example:
function getElText(el)
{
if (el.textContent) return el.textContent;
if (el.innerText) return el.innerText;
var x = el.childNodes;
var txt = '';
for (var i=0, len=x.length; i<len; ++i){
if (3 == x[i].nodeType) {
txt += x[i].data;
} else if (1 == x[i].nodeType){
txt += getElText(x[i]);
}
}
return txt.replace(/\s+/g,' ');
}
--
Rob