简体   繁体   中英

Retrieve custom html attributes in javascript function. No jquery please

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.

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 .

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,
        }
    }()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM