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>
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.
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.
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.
Examples of attribute data include sorting and counting the number of blemishes in a particular product (defects), and the number of nonconforming pieces (defectives).
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With