Da Silva
Da Silva

Reputation: 229

adding an extra attribute inside html tag through javascript

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 array [post, get, search] for each tags respectively. Is it possible to do that using javascript??

I would also like to knw what if the input was hash instead of array like

 {"post" : ["0","1"], "get": ["0","2"], "search": ["2","1"]} 

Upvotes: 0

Views: 102

Answers (3)

Alnitak
Alnitak

Reputation: 339786

var attrs = ['post', 'get', 'search'];
for (var i = 0, n = attrs.length; i < n; ++i) {
    var el = document.getElementById('slide' + (i + 1));
    el.setAttribute('key', attrs[i]);
}

Alternatively, if you are using jQuery (and assuming that only these three elements have the slide class):

var attrs = ['post', 'get', 'search'];
$('.slide').attr('key', function(i) {
    return attrs[i];
});

The updated part of the question (using an object "hash" instead of an array) wouldn't work because an object has no defined ordering. You can get the labels but they will not appear in a deterministic order:.

var myobj = {"post" : ["0","1"], "get": ["0","2"], "search": ["2","1"]};
var attrs = Object.keys(myobj);
... // as above

See the MDN site for documentation for Object.keys, including a shim for older browsers.

Upvotes: 1

insomiac
insomiac

Reputation: 5664

Set Attribute is what you are looking for :

https://developer.mozilla.org/en-US/docs/DOM/element.setAttribute

var d = document.getElementById("slide1"); 
d.setAttribute("key", "post");

Upvotes: 0

Asciiom
Asciiom

Reputation: 9975

Yes it's possible, just use element.setAttribute() like this:

var element = document.getElementById("slide1");
element.setAttribute('key','post');

Upvotes: 1

Related Questions