Da Silva
Da Silva

Reputation: 229

adding a custom key in to html tag

assume we have a set of html tags like

<div id="slide1" class="slide"></div>
<div id="slide2" class="slide"></div>
<div id="slide3" class="slide"></div>

I am trying to add an extra attribute in to the div tag like key='post' from the hash {"post" : ["0","1"], "get": ["0","2"], "search": ["2","1"]} for each tags respectively. so that it looks like,

<div id="slide1" class="slide" key="post"></div>
<div id="slide2" class="slide" key="get"></div>
<div id="slide3" class="slide" key="search"></div>

Is it possible to do that using javascript??

The code that I came up with looks like

for(key in hashArray){
var el = document.getElementsByID('slide' + (slideNumber));
el.setAttribute('key', key);
slideNumber++;
}

but im getting an error document.getElementByID is not a function

Upvotes: 0

Views: 3265

Answers (3)

RobG
RobG

Reputation: 147453

The use of non–standard attributes or properties is recommended against for the usual reasons — behaviour in different user agents is not specified, possible conflict with custom properties of other programs and future additions to standard attributes and properties and so on.

As pointed out in other answers, you can use data- attributes, but even they have the above issues for older browsers. In the OP, I can't see any benefit to using setAttribute over direct property access:

el['data-key'] = key;

(It would have been more convenient if the W3C had chosen underscore as the delimiter instead of hyphen.)

Using properties, the value can be any type whereas setAttribute only allows strings.

Another option is to store values in an object or array and get them by some reference (e.g. the element ID), which also allows values to be a type other than string.

Upvotes: 0

moonwave99
moonwave99

Reputation: 22812

Use custom data attributes [e.g. data-key], then you are perfectly right.

EDIT: your code will look like:

var slideNumber = 1;

for(key in hashArray){
    var el = document.getElementById('slide' + (slideNumber));
    el.setAttribute('data-key', key);
    slideNumber++;
}

Working fiddle here.

Upvotes: 2

bfavaretto
bfavaretto

Reputation: 71939

You're getting that error because the correct method name is getElementById, singular.

That said, your code should work. However, I recommend using data-key instead of key as the attribute name, so your HTML remains valid (valid HTML5).

Upvotes: 0

Related Questions