0

I try to use jQuery to modify the HTML template.

For example:

var d = '<div class="a"><div class="b"></div><div class="c"></div></div>';

var html = $(d).find(".b").html("BBBBB");

console.log(d);   // I want to get the new html 

In above, I want to get

'<div class="a"><div class="b">BBBBB</div><div class="c"></div></div>'

How can implement the case? Please suggest.

4
  • Try console.log(html) Commented Dec 2, 2014 at 5:28
  • why not directly use $('.b').html("BBBBB") Commented Dec 2, 2014 at 5:28
  • d is a variable and not DOM element. So it has no .html() method on it. What you actually want to achieve? Commented Dec 2, 2014 at 5:29
  • Because html string in a variable, not in brower document, I just can get it by find. @Aditya Commented Dec 2, 2014 at 5:36

2 Answers 2

9

So here is the code:

var d = '<div class="a"><div class="b"></div><div class="c"></div></div>';

var html = $(d).find(".b").html("BBBBB").end()[0].outerHTML;

console.log(html);

Note the key is to use .end(), which will pop off the context of <div class="b"> created by the .find() operation and return you to just $(d), which then allows you to get the full HTML using .outerHTML on the raw DOM node.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct answer and by far the best way to achieve it, +1
0
var d = '<div class="a"><div class="b"></div><div class="c"></div></div>';

$('.a').find(".b").html("BBBBB");
var newD = $('.a').parent().html();

console.log(newD);

You are writing into a DOM element not a variable. You need the again fetch the modified DOM element.

Comments

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.