Retrieve form's “name” attribute in Javascript

2019-06-22 13:03发布

问题:

I have something like this HTML structure :

   <form name="myvalue" id="hello">
      <input type="text" name="name" />
    </form>

I'd like to retrieve the form's name attribute in Javascript, with a cross browser solution.

Obviously,

document.getElementById("hello").name 

won't work because it will return the corresponding input object.

Under chrome, following code works, but I didn't succeeded to find the equivalent for Internet Explorer 8

document.getElementById("hello").getAttribute("name")

Thanks in advance !

Frédéric

回答1:

I think this oughtta work

document.getElementById("hello").attributes["name"].value;

tests ok in IE8, which is all I have. you might have to do some browser checking and pick your approach as needed.

edits: actually, your example works fine for me in IE8 too. but not ie7.



回答2:

Try this:

function getFormName (formElement) {
  if (!formElement) return;
  var a=formElement.attributes;
  for (var i=a.length; i--;) {
    if (a[i].name=='name') return a[i].value;
  }
}

Not sure if it will work in IE. Should work everywhere else.