user1716672
user1716672

Reputation: 1073

Jquery .html() replacing everything

I want to replace an element's content with different content in a html string. Im getting the element via a HTML5 data attribute. The backbone template returns html_string, a long string of divs and nested divs.

var html_string = template({model:player});

var newHtml = $(html_string).find("[data-position='Forward_1']").html("<div>NEWCONTENT</div>").html();

console.log('new html is');
console.log(newHtml);

The output is:

new html is 
<div>NEW CONTENT</div> 

So everything is getting replaced..

Upvotes: 2

Views: 87

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78535

If you're just trying to find all [data-position='Forward_1'] elements, you don't need .find:

$("[data-position='Forward_1']").html("<div>NEW CONTENT</div>");

edit:

Since you are actually manipulating a HTML string with this:

$("<div> ... </div>").find("[data-position='Forward_1']").html("<div>NEW CONTENT</div>");

You need to do something with the resulting element. Either add it to the DOM:

$("body").append($(html).find("[data-position='Forward_1']").html("<div>NEW CONTENT</div>"));

Or get the resulting HTML:

var newHtml = $(html).find("[data-position='Forward_1']").html("<div>NEW CONTENT</div>").html()

Upvotes: 2

Related Questions