life in a smart mob

social networking and other stuff

getElementsByName and Div tags

I just discovered that you cannot find div tags (ed. more specifically DIV tags by name) using the getElementsByName() method of the DOM.

This is a pity as it makes it trickier to do simple styling without iterating through the entire collection of DIV elements on the page and checking the name attribute.

You can use ID of course, but in ASP.NET when you set the DIV element to runat="server", and especially when they are in controls, the ID value varies.

Anyone know of a method that does this for ALL elements?

More info here.

vtgo.net

Comments

Oleg Tkachenko said:

Are you talking about MSHTML DOM in IE? Then this methods searches not be tag name, but by name attribute value.
Try getElementsByTagName instead.
# February 9, 2004 8:36 AM

Derick Bailey said:

You actually can use getElementByID with ASP.NET, despite the unique names that are generated in controls, etc. What you need to do, though, is have your code-behind generate the script so that you can populate the proper ID name in the script.

Specifically, if you want to know the ID of a DIV tag that is in a control, and have runat="server", then use the div.UniqueName property in your codebehind to get the the actual ID of the div.

example:

[html]
<div id="myDiv" runat="server">

[codebehind vb.net]
Protected Withevents myDiv as System.Web.UI.HtmlControls.HTMLGenericControl

Private Function MyMethod() as string
Dim s as string
s = "<script language=javascript>"
s &= "var d = document.getElementByID('"
s &= myDiv.UniqueName
s &= "');</script>"
return s
End Sub
# February 9, 2004 9:08 AM

Johnny Hall said:

.UniqueName? Shouldn't that be .ClientID?

Or am I missing something?
# February 9, 2004 9:40 AM

Derick Bailey said:

Oops. You are correct, Johnny. Got my properties mixed up again.

Replace my previous comment with .ClientID instead of .UniqueName
# February 9, 2004 9:46 AM

Steven Livingstone said:

Yes - guess those are excellent points and in fact help in my solution, so thanks for reminding me.

My issue was that I had encapsulated all of my code in external scrips documents and included these so i didn't have any "code behind" as such. But I appreciate there are techniques that can be used.

I'll have a think further.
# February 9, 2004 11:52 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)