Reputation: 943
I am building a Django app and need to do some Javascript processing in the HTML Template. In order to pass values from Django's templating language into Javascript, I have saved the values into meta tags as below:
<head>
{% for candidate in candidates %}
<meta id="cand" data-id="{{candidate.id}}" data-order="{{forloop.counter}}">
<h3>{{forloop.counter}}</h3>
{% endfor %}
</head>
I then try to access the data here:
<script type="text/javascript">
var metatags = document.getElementsByTagName('meta');
for (var i = 0; i < metatags.length; i++) {
console.log(metatags[i].data-id)
}
</script>
However, an issue is thrown trying to access the data:
Uncaught ReferenceError: id is not defined
In reference to the line console.log(metatags[i].data-id)
Why is this not working, am I attempting something impossible, and is there a better or more elegant way of accessing template values in Javascript?
Thanks in advance.
Upvotes: 0
Views: 58
Reputation: 17910
You have incorrect syntax for accessing HTML attributes using JavaScript.
Two ways to access data attributes,
Using dataset
console.log(metatags[i].dataset.id)
Using getAttribute
console.log(metatags[i].getAttribute('data-id'))
Upvotes: 3
Reputation: 2852
Try accessing the property like this:
console.log(metatags[i].getAttribute("data-id"));
Upvotes: 0