0

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.

4
  • 2
    Ids have to be unique, <h3> is not a valid child of <head> Commented Dec 4, 2017 at 11:10
  • 1
    Try to use the dataset property of the element to access your id like so: metatags[i].dataset.id Commented Dec 4, 2017 at 11:10
  • data-id is not a valid js identifier, it is parsed as data - id (variable "data" minus variable "id"). Commented Dec 4, 2017 at 11:21
  • and thsi has absolutely nothing to do with django FWIW (removed tags). Commented Dec 4, 2017 at 11:22

2 Answers 2

3

You have incorrect syntax for accessing HTML attributes using JavaScript.

Two ways to access data attributes,

  1. Using dataset

    console.log(metatags[i].dataset.id)

    Learn more about dataset at MDN

  2. Using getAttribute

    console.log(metatags[i].getAttribute('data-id'))

Sign up to request clarification or add additional context in comments.

Comments

0

Try accessing the property like this:

 console.log(metatags[i].getAttribute("data-id"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.