0

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"]} 

3 Answers 3

1

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

var element = document.getElementById("slide1");
element.setAttribute('key','post');
Sign up to request clarification or add additional context in comments.

1 Comment

I'm not, I was first with my answer and then decided to adapt my example to the OP's code. Not a miracle that I end up with almost identical code.
1
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.

8 Comments

what if the input was hash instead of array like {"post" : ["0","1"], "get": ["0","2"], "search": ["2","1"]}
@SamDaSilva what do you expect the HTML output to look like in the hash example? p.s. if that's really the case, you should update your question because the answer will look quite different.
keys should have the same values as that of array..qustion updated
@SamDaSilva but what do the values inside the array represent (if anything)? An object has no order, so you can't assume that post will go into element 0.
ignore the elements inside the array...I just wanted to add a hash
|
0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.