How can I extract this table cell value?

D

D. Alvarado

Will Javascript allow me to extract the value 'NWEINETTE' (value from
first td) from the following HTML?

<tr id="lightrow" class="data">
<td class=data id='USER_NAME' nowrap><A class='data'
HREF="user_profile.jsp?LOGIN=NWEINETTE">NWEINETTE</A>&nbsp;&nbsp;&nbsp;</td>
<td class=data id='FIRST_NAME' nowrap>nancy&nbsp;&nbsp;&nbsp;</td>

<td class=data id='MIDDLE_NAME' nowrap>f&nbsp;&nbsp;&nbsp;</td>
<td class=data id='LAST_NAME' nowrap>weinette&nbsp;&nbsp;&nbsp;</td>
</tr>

Ideally, it would be great if I could find some cross-browser (IE 6+,
Netscape 7+) JS that could do the task.

Thanks, - Dave
 
A

asmo

Hi Dave,

try this:

// get a ref to the row
var theRow = document.getElementById("lightrow");
// get the first link
var theLink = theRow.getElementsByTagName("A")[0];
// your value
alert(theLink.innerHTML);

this should work in any dom compliant browser..

regards
 
M

Michael Winter

Please quote relevant text from the post you are responding to, including
who wrote that post.
// get a ref to the row
var theRow = document.getElementById("lightrow");
// get the first link
var theLink = theRow.getElementsByTagName("A")[0];
// your value
alert(theLink.innerHTML);

this should work in any dom compliant browser..

Why? The innerHTML property isn't defined as part of the DOM, though it is
supported by the "major" browsers.

A solution that is fully DOM-compliant is:

var user = document.getElementById('USER_NAME');
// value:
user.firstChild.firstChild.data

This makes a couple of assumptions:

1) The id, USER_NAME, is unique. Whilst this should be the case anyway as
id values must be unique, I don't get that impression from the HTML
provided by the OP.
2) There is no whitespace between the opening cell and link tags. If there
is whitespace, the code becomes a little more involved, but simple
nevertheless.


<tr id="lightrow" class="data">
<td class=data id='USER_NAME' nowrap><A class='data'
HREF="user_profile.jsp?LOGIN=NWEINETTE">NWEINETTE</A>&nbsp;&nbsp;&nbsp;</td>

If you need to pad an element, use the CSS padding property. With the
markup you presented, the rule

#lightrow td {
padding-right: 3ex;
}

would achieve what the non-breaking spaces do, but with the benefit of not
being a hack. A different selector might be more appropriate, depending
upon the rest of your page.

A small request when posting code: please don't use tabs. They can cause a
significant amount of wrapping. Instead, use spaces - two is probably be
the best, considering the limited width.

Mike
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top