I am L
I am L

Reputation: 4662

Passing Attributes / objects through an attribute. Javascript

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

Upvotes: 6

Views: 16450

Answers (3)

Vivien Sonntag
Vivien Sonntag

Reputation: 4639

As you tagged your question Polymer - this works for Polymer-elements :

<polymer-element object-attribute='{"alt":"json", "q":"chrome"}'>

Source : https://elements.polymer-project.org/elements/iron-ajax

Tried it for a custom element, it worked as well - unfortunately it does not work for default html-elements (e.g. divs). So maybe defining a custom-element for this might be a solution for you. Otherwise use the answers above ;)

Upvotes: 0

A. Gille
A. Gille

Reputation: 1048

From this

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

Get the attribute value

1. Javascript

var attr = document.getElementById('myelem').getAttribute('myattr')

2. JQuery

var attr = $('.myelem').attr('myelem')

String to JSON

var obj = JSON.parse(attr)

Upvotes: 0

CoderPi
CoderPi

Reputation: 13221

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

Upvotes: 5

Related Questions