51

How can I get the value of a custom attribute using JavaScript?

Like

<strong id="the_id" original-title="I NEED THIS">

I've tried .getAttribute() and jQuery’s .attr() without success.

1
  • 1
    You should be using HTML5 data-* attributes. Your current markup is invalid. Commented Sep 1, 2012 at 8:53

3 Answers 3

75

You can do it using plain JavaScript:

document.getElementById("the_id").getAttribute("original-title")
Sign up to request clarification or add additional context in comments.

1 Comment

This is the real answer
66

Adding custom attributes makes your HTML invalid. Use custom data attributes instead:

<strong id="the_id" data-original-title="I NEED THIS">
$('#the_id').data('original-title')

https://jsbin.com/akoyut/2/edit

2 Comments

This did not update for me when the data- attribute changed. $('#the_id').attr('data-original-title') gets the current value of the attribute.
HTML invalid as in not part of the spec or that it won't work? I swear I've seen custom attributes before.
3

You can get the value by using attr:

$('#the_id').attr('original-title')

1 Comment

using jquery..i've tryed it but it returns null

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.