An Attribute of a Parent Element?

P

pbd22

Hi.

Could some kind sould tell me what the javascript would be to get a
given attribute of the parent "table" element of a given element
inside that table.

So,

<table width="54">
[SNIP - LOTS OF HTML HERE]
<a href="#" onclick="Foo();">get the width attribute's value</a>
</table>

When I click on the anchor tag, it returns the number "54".

How do I do this?
 
T

The Natural Philosopher

pbd22 said:
Hi.

Could some kind sould tell me what the javascript would be to get a
given attribute of the parent "table" element of a given element
inside that table.

So,

<table width="54">
[SNIP - LOTS OF HTML HERE]
<a href="#" onclick="Foo();">get the width attribute's value</a>
</table>

When I click on the anchor tag, it returns the number "54".

How do I do this?
Give the table an ID and getElementById on it.
 
T

Thomas 'PointedEars' Lahn

pbd22 said:
<table width="54">

The `width' attribute is presentational. Use CSS instead.
[SNIP - LOTS OF HTML HERE]
<a href="#" onclick="Foo();">get the width attribute's value</a>

That element should be generated by client-side scripting:

<script type="text/javascript">
document.write('<a ...>...<\/a>');
</script>

Foo() would not be a constructor or a factory, and so should be foo().
</table>

When I click on the anchor tag, it returns the number "54".

How do I do this?

You don't, as you cannot click on a tag if not in your source code editor.

Provided that you mean a click on the `a' element there, you have to obtain
the ancestor element object reference through iteration:

function getNextAncestor(o, sElemType)
{
if (o)
{
var rxElemType;

if (typeof sElemType == "string")
{
rxElemType = new RegExp(sElemType.toLowerCase(), "i");
}

if (rxElemType)
{
while ((o = o.parentNode))
{
if (rxElemType.test(o.tagName))
{
return o;
}
}
}
}

return null;
}

function getAncestorTableWidth(o)
{
return (getNextAncestor(o, "table") || {width: -1}).width;
}

<table width="54">
...
<tr>
<td>...<a
href="#"
onclick="window.alert(getAncestorTableWidth(this)); return false"
get the width attribute's value</a>...</td>
</tr>
...
</table>


HTH

PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top