1

This w3schools page mentions the HTML DOM createElement() Method. For example, you can create a button by

var btn = document.createElement("BUTTON");

Now, I want to attach some information to this button. What is the appropriate way to do it? If I want to attach the array ["one", "two", "three"], can I just do

btn.myOwnInformation = ["one", "two", "three"]

?

Mika H.
  • 4,119
  • 11
  • 44
  • 60
  • The DOM isn't for data, it's for display. You probably shouldn't use it to store arbitrary data. – user229044 Sep 06 '13 at 01:49
  • @meagar But I want to store data in the button, not the DOM. – Mika H. Sep 06 '13 at 01:50
  • The button is in the DOM. It's a DOM element. As you said, "the HTML **DOM** createElement method". If you really want to do this, you could look at how jQuery stores arbitrary data with it's `data` method. It's open source. – user229044 Sep 06 '13 at 01:51

3 Answers3

1

You can use the html5 data attribute to add arbitrary data to DOM elements.

btn.setAttribute('data-array','one,two,three');

Get the data back by using split;

Here's an example: jsFiddle

Dylan Holmes
  • 772
  • 4
  • 8
1

That certainly works if you try, but it is usually discouraged, for a few reasons:

  • Separation of concerns
    The DOM is meant for display structure and logic, so any other kind of data is better stored separately.

  • Collision with future DOM specifications
    What if you choose a property or method name that becomes a standard in the future? Your code may become buggy on future browsers.

  • Browser compatibility
    Old browsers (IE 6/7) could leak memory when data was attached to DOM objects. It's less of a problem now, but since JavaScript objects provided by browsers ("host objects") are less controllable, I suggest avoiding to extend them (or their prototypes) unless you know what you're doing.

For those reasons, libraries like jQuery use a separate structure to store arbitrary data (and also event handlers) and relate them to DOM elements. For the same reasons, jQuery wraps selected DOM nodes in jQuery objects, instead of directly extending the DOM interface with methods like append, css, etc.

Related questions and references

Community
  • 1
  • 1
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
0

If you are willing to use jQuery

there's a function which can match you requirement

jQuery.data()

code can be written like this:

var $btn = $('<input type="button" value="buttonName">');
$btn.data('keyName',["one", "two", "three"]);  //insert data
var getData = $btn.data('keyName');  //get data by keyName

(Sorry, I don't have enough reputation to use commend)

Dennis Shen
  • 61
  • 1
  • 6