m b
m b

Reputation: 178

Using an html "data-" attribute

Consider a line such as this:

<div id='abc' onclick='DoSomething(this.id)'></div>

Now, suppose it's expanded to be something more like this:

<div id='abc' data-something='whatever' onclick='DoSomething(this.id)'></div>

There's no functional difference here yet, but this is my question. I'm looking for a way to pass the value of 'data-something' to the DoSomething function instead of the id. I can't seem to find a method of doing this? Is it possible?

Something like the following would be nice, but of course it's not how it works. (I'm only including it to help illustrate the intended goal.

<div id='abc' data-something='whatever' onclick='DoSomething(this.data-something)'></div>

Upvotes: 7

Views: 1526

Answers (4)

Zauker
Zauker

Reputation: 2394

if you want consider jQuery you could convert your code in somethings like that:

html

<div id="abc" data-something="whatever">click here</div>

jQuery

jQuery(document).ready(function($) {
    $('#abc').on('click', function () {
        DoSomething($(this).attr('data-something'));
    });
});

or better

jQuery(document).ready(function($) {
    $('#abc').on('click', function () {
        DoSomething($(this));
    });
});

function DoSomething(obj){
    alert(obj.attr('id'));
    alert(obj.attr('data-something'));
}

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382168

You can do

DoSomething(this.dataset.something)

But it's generally recommended to separate the javascript part and the HTML, which is especially easy when your element has an id :

<div id='abc' data-something='whatever'></div>
<script>
    document.getElementById('abc').onclick = function(){
        DoSomething(this.dataset.something)
    }
</script>

On Internet Explorer, support for dataset is incomplete. On IE10-, You need to use

DoSomething(this.getAttribute('data-something'))

Upvotes: 10

user1386320
user1386320

Reputation:

You should use getAttribute method:

<div id='abc' data-something='whatever' onclick='DoSomething(this.getAttribute("data-something")'></div>

But I highly suggest that you aviod inline javascript delegation to elements. You should better use DOM or jQuery for that and note that jQuery has a method for easier data-* attributes handling.

Upvotes: 1

musefan
musefan

Reputation: 48425

You should be able to do this.getAttribute("data-something"), like so:

<div id='abc' data-something='whatever' onclick='DoSomething(this.getAttribute("data-something"))></div>

or you can use this.dataset.something.

Here is my source

Upvotes: 5

Related Questions