Skip to content Skip to sidebar Skip to footer

Can A Variable Be Stored Within An Image Or Div Tag?

I've managed to create a huge div that contains many small divs appended to it, so it creates a grid. My goal is to be able to store two variables within each of the smaller divs (

Solution 1:

you can create infinite data-[whatever] attributes to store any variables you'd like

you can then access this variable with element.getAttribute('data-example-name');

here's an example:

var testElement = document.getElementsByClassName('test')[0];
var result = document.getElementById('result');
result.textContent = testElement.getAttribute('data-my-tag');
.test {
  background: blue;
  color: white;
  padding: 20px 30px;
  width: 300px;
  text-align: center;
}
<div class="test" data-my-tag="5">
  <h2>testing a made-up attribute, <br>
  data-my-tag = 
    <span id="result">{should be a number}</span>
  </h2>
</div>

same code via jsfiddle


Solution 2:

I can think of two ways to store information with each div:

(1) Storing a hidden <input type="hidden" value="something" /> file in the div

(2) Adding the data-something="Some information" attribute to the div. Code would look like:

div.dataset.something = "Some information to pass along";

Here's more information on (2):

Set data attribute using JavaScript

https://developer.mozilla.org/en/docs/Web/Guide/HTML/Using_data_attributes

https://www.sitepoint.com/use-html5-data-attributes/


The data attribute can be used with many HTML tags, including <img data-desc="Photo of a dog" />


Solution 3:

Actually, you can add any property (or even function) to your element. Like if you have a div variable for your element, you can do just

div.someProperty = someValue;
div.myFunction = function(...) { ... };

The only thing you should care about is not to overwrite some "system" property like style and others.


Post a Comment for "Can A Variable Be Stored Within An Image Or Div Tag?"