Passing Attributes / objects through an attribute. Javascript

11,094

You will have to* use JSON.parse() and your string will have to be in a valid JSON-Format.

var element = document.getElementById('myelem')
var attributeContent = element.getAttribute('data-myattr')
var object = JSON.parse(attributeContent)
<div id="myelem" data-myattr='[{ "title": "hello", "author": "mike" }, { "title": "world", "author": "hellen" }]' />

*You could also do var object = eval(attributeContent) without the need of a JSON-String. But have a look at "Why is using the JavaScript eval function a bad idea?"


Finally I'd like to suggest to use the <script> tag instead of a attribute to pass JavaScript-Objects via your HTML-Code:

<script>
    var myStuff = [{ title: 'hello', author: 'mike' }, { title: 'world', author: 'hellen' }, {}];
</script>

You will then be able to access myStuff in your JavaScript-Code

Share:
11,094
I am L
Author by

I am L

I don't have any will to live aside from working hard as a programmer/web developer to support my parent's needs. They're the only thing I have.

Updated on July 04, 2022

Comments

  • I am L
    I am L almost 2 years

    Is there a way to pass an array or object through an attribute? like:

    <div id="myelem" myattr="{ title: 'hello', author: 'mike'}, { title: 'world', author: 'hellen'}, {...}"/>
    

    I just tried this using javascript, but only the first object are being returned, i would like to have something like this:

    for(let i=0; i<this.myattr.length; i++){
      console.log(this.myattr.title);
    }
    

    Any ideas? Thankyou