Search code examples
javascriptjqueryhtmlrel

Rel attribute in jQuery


I want to create dynamic html which needs to render as code given below:

<a rel="{gallery: 'gal', smallimage: 'a',largeimage: 'b'}" href="javascript:void(0);"><img src="x1.jpg"></a>

What I wrote following code in jQuery to achive above:

for(i=1; i<=4; i++){
    var rela="{gallery:'gal', smallimage:'a', largeimage: 'b'}";
    html += "<a href='javascript:void(0);' rel='"+rela+"' ><img src='x"+i+".jpg' /></a>";
}

But when it's executed it renders as below:

<a 'b'}'="" largeimage:="" smallimage:'a',="" gal',="" rel="{gallery:" href="javascript:void(0);"><img src="x1" class="img1"></a>

Solution

  • Using attributes to store data on objects isn't exactly a smart idea as you found out yourself, it doesn't work as you might want it to work. Especially json.

    In your case you're trying to store json? Or an object with qoutes in it in the html, the browser however will treat the first qoute it encounters as a closure of the rel attribute.. messing stuff up bigtime.

    Store the different properties in a seperate data attribute, or considder storing the items in a js variable and the anchor an id. When you need the data again you use the id on the anchor to recapture the data from the js variable. (read more here on data attributes).