aslamdoctor
aslamdoctor

Reputation: 3935

How to concat html object to html string using jquery?

I have created a loop and below is the part of the code between that loop

--- Loop Starts ---

var aElement = $('<a>');
aElement.attr('href', '#');
aElement.text(title);

aElement.click(function() {
    alert("Hello World);
});

video_list_html += '<tr>' +
                        '<th scope="row">' + count + '</th>' +
                        '<td>' + aElement + '</td>' +
                    '</tr>';
--- Loop Starts ---

But as aElement is an object, it doesn't attach as html tag to the video_list_html but it attaches like this

[object Object]

How do I fix this, so that it attaches inside the video_list_html and also the .click() event stay working.

Upvotes: 1

Views: 2912

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337646

The issue is because you cannot append an object to a string. The object gets coerced, ans the result is, as you've seen, [Object object].

A better solution to this problem would be to append the new HTML as one entire string, then use a delegated event handler to catch the events from those dynamically added elements. Try this:

var data = [{
  videoId: 'abc123',
  title: 'Video #1'
}, {
  videoId: 'xyz987',
  title: 'Video #2'
}]

var video_list_html = data.map(function(o, i) {
  return '<tr><th scope="row">' + i + '</th><td><a href="#" data-videoid="' + o.videoId + '">' + o.title + '</a></td></tr>';
}).join('');

$('#yourTable').append(video_list_html).on('click', 'a', function(e) {
  e.preventDefault();
  console.log($(this).data('videoid'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="yourTable"></table>

Upvotes: 0

Killer Death
Killer Death

Reputation: 459

Try using aElement[0].outerHTML instead of aElement. Leave click handler as is.

Upvotes: 1

Related Questions