1
<input  id="test" value="123" name ="test"  verify="NOTNULL">

In some HTML, I saw the input tag has the attribute verify. How to add it to the input tag?

I tried the code

alert(document.getElementById("test").verify)  

the result is undefined.

How do I add a new attribute to the element?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Adding an attribute to an HTML tag is typically done on the server. Are you saying that the attribute is already on the HTML tag, and you need to extract its value from the JavaScript DOM element? –  Jul 12 '13 at 19:32
  • 2
    Not all HTML attributes map to DOM properties, especially not custom attributes. You should use `data-*` attributes for custom ones. See http://stackoverflow.com/q/992115/218196. Btw, the attribute *is* already added to the element, because you defined it in the HTML. It seems you want to know how to *access* it. If you really want to *add* it programmatically, you can use `setAttribute`. – Felix Kling Jul 12 '13 at 19:34
  • ...ah, I see the HTML was unformatted and lost. Yeah, like @Felix said, it would be good to use `data-` attributes instead. –  Jul 12 '13 at 19:37
  • thank you,i used 'getAttribute' and get the value of the verify. – user2227242 Jul 14 '13 at 06:41

2 Answers2

5

If you mean to say that the html input element has a [verify] attribute, then you can access the attribute via getAttribute():

HTML:
<input id="test" verify="test" />
JS:
document.getElementById('test').getAttribute('verify'); //test
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • 2
    Note that the `[verify]` attribute is not a valid HTML attribute as far as I'm aware. [`[data-*]` attributes should be used for passing custom attribute values](http://www.w3.org/html/wg/drafts/html/master/single-page.html#embedding-custom-non-visible-data-with-the-data-*-attributes). – zzzzBov Jul 12 '13 at 19:37
1

Adding an attribute with pure Javascript is done via setAttribute

document.getElementById("test").setAttribute("verify","verified");

And to read it:

document.getElementById("test").getAttribute("verify")
Icarus
  • 63,293
  • 14
  • 100
  • 115