1

I am trying create a new Anchor tag in Jquery with some attribute and storing it in variable, but when i concatenate it with other variable and append to Dom it gives [OBJECT OBJECT]

JsFiddle for the Same : http://jsfiddle.net/T8q6T/

var a_name = "Sathwick Rao ([email protected])^$^4083372345";
var _name = a_name.split('(')[0];
var _part1 = a_name.split('(')[1];
var _email = _part1.split(')')[0];
var htmlElement = $('<a>('+_email+')</a>').attr('href','mailto:'+_email);
$('#shara').html(_name+' '+htmlElement);

3 Answers 3

1

You can't concatenate a string with an object like that. Separate the two statements like this:

http://jsfiddle.net/E2Rur/

$('#shara').html(_name).append(htmlElement);
Sign up to request clarification or add additional context in comments.

1 Comment

It's probably better to avoid 2 DOM reflows. Chaining DOM changing operations is quite a bad habit ;) Obviously this single case will not affect performance, however when it's part of a bigger application where this sort of approach is used many times, it could be harmful.
0

It's because you are trying to concatenate an object with a string. Therefore, the object gets implicitly converted to it's string representation by it's toString function.

E.g.

var div = document.createElement('div');
'some string' + div.toString(); //"some string[object HTMLDivElement]"
'some string' + div; //"some string[object HTMLDivElement]"

If you want to concatenate the outerHTML of the element with some other HTML string that is possible however.

$('#shara').html(_name + ' ' + htmlElement.prop('outerHTML'));

However it's not necessary the most optimal or clean way when it's not necessary.

$('#shara').append($('<span>').addClass('name').text(_name).add(htmlElement));

As you may have noticed, I add the htmlElement to the set and perform a single append operation rather than chaining two append calls. That's to avoid multiple DOM reflows, which are quite expensive.

If you do not want the wrapping span and use the same solution, you can also do:

$('#shara').append($(document.createTextNode(_name + ' ')).add(htmlElement));

1 Comment

@SJ-B Glad I could help. The other answer might be shorter, however it's causing two DOM reflows which is not as efficient. It's a good practice to avoid them as much as possible, even if you would probably not notice much difference in this case ;)
0

To force the variable htmlElement to store a string, I sometimes hack it like this

 var htmlElement = $('<a>('+_email+')</a>').attr('href','mailto:'+_email)+"";
 $('#shara').html(_name+' '+htmlElement);

1 Comment

That will produce the same undesired result. Please see my answer.

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.