Reputation: 5841
I am using jquery right now to get the value for the id, like in the code bellow:
<ul class="trf noborder" data-id="6581">
</ul>
var ID = $("ul.trf").data('id');
How can I do this using pure javascript? Do I need to add a span class or something?
Ty
Upvotes: 1
Views: 118
Reputation: 4338
There are several ways to do it with pure javascript depending on your needs and what kind of performance you expect. Here is one way using an ID:
<ul class="trf noborder" data-id="6581" id="myDiv">
</ul>
<script type="text/javascript">
var id = document.getElementById("myDiv").getAttribute("data-id");
</script>
Or you can try this if you want to target a specific UL without any ID
<ul class="trf noborder" data-id="6581">
</ul>
<script type="text/javascript">
var id = document.getElementsByTagName("ul")[0].getAttribute("data-id");
</script>
But you will have to make sure that you use the right index, here it will retrieve the first UL on your page. You could also wrap it in another container:
<div id="container">
<ul class="trf noborder" data-id="6581"></ul>
</div>
<script type="text/javascript">
var container = document.getElementById("container");
var id = container.getElementsByTagName("ul")[0].getAttribute("data-id");
</script>
And it will use the first UL inside of that container. Or the third if you do it like this:
var id = container.getElementsByTagName("ul")[2].getAttribute("data-id");
It's based on the array index, 2 in this case (0, 1, 2 = third element)
If you don't want jQuery but still can be willing to use a library, look at http://sizzlejs.com which is a great selector engine (actually used by jQuery). With Sizzle you could do it like this:
var id = Sizzle("ul[data-id]")[0].getAttribute("data-id");
To get the data-id of the first UL on the page that has a data-id attribute specified.
Upvotes: 2
Reputation: 30473
getData: function(el, attr) {
attr = 'data-' + attr;
var result = (el.getAttribute && el.getAttribute(attr)) || null;
if(!result) {
var attrs = el.attributes;
var length = attrs.length;
for(var i = 0; i < length; i++)
if(attrs[i].nodeName === attr)
result = attrs[i].nodeValue;
}
return result;
}
var el = document.getElementsByClassName('trf')[0];
var id = getData(el, 'id');
Upvotes: 1
Reputation: 3111
You can read attribute with getAttribute function. But you should gather element itself, calling getElementById or getElementsByTagname functions.
Upvotes: 1
Reputation: 3404
You can use
element.getAttribute('attribute_name')
in pure JavaScript to get the value of any data attribute's value.
Example can be found here : Click Here
Upvotes: 2