2

I have a <span> element that I am reading with JavaScript. The element is like the following one:

<span key="789">
  <input id="ctl00_cphBody_gvContact_ctl09_cbox" type="checkbox" name="ctl00$cphBody$gvContact$ctl09$cbox">
</span>

I need to get the value for the "key" attribute. If I try to get the inner HTML of the HTML element, it returns the HTML of the inner checkbox.

5
  • 3
    @David Wolever - As silly at it seems, I don't think it is too localized. The OP does not know how to access a custom DOM property. The weird number and example HTML are irrelevant, IMO. Commented Aug 6, 2011 at 5:20
  • You're right — the general question is fine (as evidenced by the myriad of similar questions the Google search I linked to shows). However, the specific wording of this question (“how to read key in span”) is what makes it too localized, in my opinion. Commented Aug 6, 2011 at 5:29
  • @David, if you have this opinion why not simply you edit the question and make it correct. Commented Aug 6, 2011 at 5:43
  • Two reasons: that would make it an exact duplicate (so I'd have to close “exact duplicate”) and it wouldn't help you, OP, understand the types of questions Stack Overflow is trying to encourage. Commented Aug 6, 2011 at 5:54
  • Note that there is nothing “wrong”, per se, with having a question closed — it's simply an indication that the question in its current form isn't right for Stack Overflow (as opposed to a down vote, which means “this is a low quality question”). Commented Aug 6, 2011 at 5:57

2 Answers 2

9

Using jQuery:

$('span').attr('key').

Using pure javascript

document.getElementsByTagName('span')[0].getAttribute('key')
Sign up to request clarification or add additional context in comments.

1 Comment

In addition to this, I'd like to say that you should really store the key as data-key='789'. This is the new HTML5 specification and does not hurt to begin using it immediately. In newer versions of jQuery, you would access this with $('span').data('key')
1

JQuery makes it really easy. See the .attr method

You'll probably want to assign an id or class to that span so that you can select it specifically:

<span id="idOfSpan" key="blah">...</span>

var spanKey = $('#idOfSpan').attr('key')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.