Reputation: 232
I am trying to figure out how to get the quoted content of an HTML tag.
Here's the HTML I've got :
<div class="html5videoplayer" id="player1" data-files="aGV5IG1hbg=="></div>
I'm trying to get the content of the data-files
attribute.
The main problem is that I have no clue how you could get the contents of a specific attribute. I know I can identify the entire class or id by using getElementById()
or getElementsByClassName()
but to get a specific attribute is unknown for me.
If you have a clue for me I'd greatly appreciate it. Thank you!
Upvotes: 3
Views: 524
Reputation: 47091
With jQuery :
var dataFiles = $('#player1').attr("data-files");
Without jQuery :
var dataFiles = document.getElementById("player1").getAttribute("data-files");
Both options should work in any browser!
You can try both of them at this Fiddle.
Upvotes: 1
Reputation: 1427
You can use JQuery data()
function OR attr()
function to get content
<div class="html5videoplayer" id="player1" data-files="aGV5IG1hbg=="></div>
<script>
$(document).ready(function(){
var result_dataFun = $("#player1").attr("data-files");//Using data() function
var result_attrFun = $("#player1").data("files"); //Using attr() function
alert(result_dataFun);
alert(result_attrFun);
});
</script>
Result :
aGV5IG1hbg==
Upvotes: 0
Reputation: 1456
In this case you can access the content of data-files with the jquery attr() function
$("[data-files]").attr("data-files")
Upvotes: 0
Reputation: 15846
Use data() function in jQuery.
$('#player1').data('files');
In simple JS,
var data = document.getElementById('player1').dataset.files;
But for older browsers like IE8 you cannot get it using dataset,
So you can use this workaroud (only need this if you are not using jQuery, then simply use the first suggestion.),
var data = document.getElementById('player1').getAttribute('data-files');
Upvotes: 4
Reputation: 74738
You can use dataset:
var files = document.querySelector('#player1').dataset.files;
data-*
is attribute from html5, which can be used to store specific/particular data for element. If you have multiple data-*
attributes on your element then it will return an object with all the keys and values.
Upvotes: 2