Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 529
m b Avatar asked Jul 19 '13 15:07

m b


People also ask

How do you use data attributes in HTML?

Adding a data attribute is easy. Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.

What is an HTML attributes and how we use it?

An HTML attribute is a piece of markup language used to adjust the behavior or display of an HTML element. For example, attributes can be used to change the color, size, or functionality of HTML elements.

How can use data attribute value in CSS?

Getting a data attribute's value in CSS # You can access the content of a data attribute with the attr() CSS function. In every major browser, it's use is limited to the content property. For example, let's say you wanted to add some content dynamically to a component based on a data attribute value. You could do this.

What is an example of a data attribute?

Examples of attribute data include sorting and counting the number of blemishes in a particular product (defects), and the number of nonconforming pieces (defectives).


1 Answers

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'))
like image 74
Denys Séguret Avatar answered Sep 24 '22 12:09

Denys Séguret