1

Here, I'm trying to define a HTML attribute called zerg, and display it when a paragraph is clicked, but instead, it displays "undefined" when it is clicked. What's wrong with the code that I've written, and what is the correct way to do this?

<p onclick = "alert(this.zerg);" zerg = "Why doesn't this work?">Click here!</p>
Anderson Green
  • 30,230
  • 67
  • 195
  • 328
  • 3
    Attributes are not the same as properties. `this.getAttribute("zerg");` though it's not a valid attribute. You can use `data-zerg` to at least be HTML5 compliant. –  May 11 '13 at 01:51
  • 1
    As a little background read: http://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice and http://en.wikipedia.org/wiki/Unobtrusive_JavaScript – Xotic750 May 11 '13 at 01:56
  • 2
    "Unobtrusive JavaScript" is a religion. –  May 11 '13 at 01:57
  • 1
    I seem to be very religious. :P – Xotic750 May 11 '13 at 02:10

4 Answers4

5

In order to be HTML5-compliant, the attribute should be named data-zerg instead of zerg. Try this:

<p onclick = "alert(this.getAttribute('data-zerg'));" data-zerg = "Now it works as intended!">Click here!</p>

http://jsfiddle.net/QrrpB/1340/

Anderson Green
  • 30,230
  • 67
  • 195
  • 328
3

try this:

<p onclick = "alert(this.getAttribute('zerg' ));" zerg = "Why doesn't this work?">Click here!</p>
3

You may use the getAttribute() method:

<p onclick = "alert(this.getAttribute('zerg'));" zerg = "Why doesn't this work?">Click here!</p>
Wayan Wiprayoga
  • 4,472
  • 4
  • 20
  • 30
0

You can try this :-

   <p onclick = "javascript:alert(this.getAttribute('zerg'));" zerg="Now it works as 
intended!">Click here!</p>

this refer to current element. So , you can use this.getAttribute() as inline code.

JDGuide
  • 6,239
  • 12
  • 46
  • 64