[Javascript] javascript and id's
Paul Novitski
paul at novitskisoftware.com
Tue Oct 4 12:08:42 CDT 2005
At 09:34 AM 10/4/2005, Anthony Ettinger wrote:
...
>I want to change the value of an attribute of an input
>field:
>
><input type="text" name="foo">
>
>want to change it to
>
><input type="text" name="bar">
>
>What I ended up doing was giving the <input> element
>an id="searchfield", and then looping through it's
>attributes using '.attributes' on the input object,
>and testing the name of the attribute == 'name'. and
>then replacing it's value with 'bar'.
>
>Is there an easier way to access an attribute of an
>element if I know it's direct path?
>
>Seems to me very inefficient to have to do looping if
>it's not necessary.
Anthony,
Giving an element an id so you can point to it without searching is
great if your situation allows. I can think of situations in which I
might choose to search (loop) for an element -- e.g., if I
potentially needed to select more than one element in a group, or if
I needed to select on the basis of attributes other than id or
tagName, or if I didn't have control over the markup. In your case
you need to select an element by its name attribute and therefore
have to either search or add an id.
However, I can't see why you'd need to loop through the attributes in
the target element. If you're using id to point to the element, you
don't need to test for the current name so just set the name and
you're done. If you've found the target element by searching, you
can use the getAttribute() method to check each element's name as you
cycle through them.
__________________________
Either:
< input id="inputFoo" name="foo" ... />
// point to it
var oInput = document.getElementById("inputFoo");
// if it exists, set its name
if (oInput) oInput.setAttribute("bar");
__________________________
Or:
< form id="foo" ... >
< input name="foo" ... />
</form>
// point to the form
var oForm = document.getElementById("foo");
// bail if not found
if (!oForm) return;
// get array of all INPUT elements
var aInputs = oForm.getElementsByTagName("INPUT");
// search for foo
for (var iInput = 0; iInput < aInputs.length; iInput++)
{
// if found...
if (aInputs[iInput].getAttribute("name") == "foo")
{
// change name
aInputs[iInput].setAttribute("name", "bar");
// exit the FOR loop
break;
}
}
__________________________
Caveat: Seat-of-the-pants coding, needs testing.
Paul
More information about the Javascript
mailing list