0

I have created a button as

<button type="button"  name="createTask" id="createTaskNOw" class="createButton" createtype="task" onclick="components.init(this)" >Add Task</button>

I also have an external javascript file which have this component.init method where I want to retrieve the custom attribute. So I am doing the following

var components = function(){
    var _init = function(attributes){
        console.log("Method Executing:Compnents.init",attributes.createtype);
            }   
    return {
        init:_init,
        }
    }()

When I am logging attributes like name or id I can see the expected result but logging createtype is showing undefined. Is there anything wrong in custom attributes.

2

3 Answers 3

2

You can retrieve attributes with the Element.getAttribute() function.

Here's a working example snippet:

var div = document.getElementById('test');
div.innerHTML = div.getAttribute('data-val'); //returns a string
<div id="test" data-val="5"></div>

This will place 5 within the <div> element. Working example on JSFiddle.

4
  • .getAttribute(...) will yield the string "5" and not the number as .dataset.val would do - HTML5 Custom Data Attributes (data-*)
    – Andreas
    Commented Feb 15, 2015 at 1:52
  • 2
    True, but dataset has odd compatibility with IE 9 & 10. It's supported in 11+, though.
    – user3886234
    Commented Feb 15, 2015 at 1:55
  • 1
    @Andreas Yes, dataset is better. But I don't think it converts to a number. dataset returns a DOMStringMap, which is a map of DOMStrings, which are Strings in JavaScript.
    – Oriol
    Commented Feb 15, 2015 at 2:08
  • @Oriol You're right. I've only used it lastly with jQuerys .data() which tries to convert the value to the correct type... - jsfiddle.net/6u3ucc6q
    – Andreas
    Commented Feb 15, 2015 at 2:17
1

try replacing attributes.createtype with attributes.getAttribute('createtype') in your function

var components = function(){
    var _init = function(attributes){
        console.log("Method Executing:Compnents.init", attributes.getAttribute('createtype'));
            }   
    return {
        init:_init,
        }
    }()
1

Your current approach is a bit old school. I recommend you adopt HTMLElement.dataset, which is designed for custom attributes in HTML5.

It looks like:

<button type="button" data-createtype="task">Add Task</button>

You can get and set the attribute with JS:

var button = document.querySelector('button');
console.log(button.dataset.createtype); // task
button.dataset.createtype='announce';
console.log(button.dataset.createtype); // announce

As of @jfriend00 mentioned, this feature is only partially supported on IE10 and below. In that case you could shim it with getAttribute() like before.

1
  • 2
    FYI to the OP. dataset requires IE11.
    – jfriend00
    Commented Feb 15, 2015 at 2:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.