-1

I am trying to add object to attribute using javascript but it is passing as object object.

var choice = {'name':'one',id:1}

COde

return '<a href="/users?userId='+
  choice.id+'" class="tool-tip" title="'+
  choice.name+'"><span data-desc="'+
  choice+'">'+this.label(choice)+'</span></a>';

it is creating as

<a href="/users?userId=1" class="tool-tip" title="userName">
<span data-desc="Object Object"></span></a>

Where i am dong wrong?

5
  • Do not use a string to create elements. Commented Aug 29, 2016 at 12:32
  • choice is an object, what did you expect? Post this.label too Commented Aug 29, 2016 at 12:33
  • @epascarello what else i can use? Commented Aug 29, 2016 at 12:33
  • @mplungjan its an object, on click of element i have to do some operations Commented Aug 29, 2016 at 12:34
  • What is this.label()? What do you need to write inside data-desc attribute? This are the details that you need to provide if you want a valid answer. See: stackoverflow.com/help/how-to-ask Commented Aug 29, 2016 at 12:35

1 Answer 1

2

When manipulating the DOM via Javascript, there is absolutely no need to go through the intermediary simplified HTML representation. Create DOM objects directly with arbitrary properties:

var link = document.createElement('a');
link.href = '/users?userId=' + choice.id;
link.classList.add('tool-tip');
link.title = choice.name;

var content = document.createElement('span');
content.desc = choice;
content.textContent = this.label(choice);

link.appendChild(content);

return link;

And then appendChild this link to some other DOM element…

If you absolutely need choice to be part of dataset (data-*="…") because some other component depends on it… well, dataset can only hold strings, not objects, so you would have to at least agree that the value is a JSON string:

link.dataset.desc = JSON.stringify(choice);
Sign up to request clarification or add additional context in comments.

2 Comments

content.dataset.desc = choice STILL gives <span data-desc="[object Object]">
Ah, yes, I forgot that dataset is a map of strings… Updated. @Kunal

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.