4

I have html code saved in a variable called myHtml

<div>
    <p data-id="1">A</p>
    <p data-id="2">B</p>
    <p data-id="3">C</p>
</div>

I need to change the value of before appending this to html.

My code doesn't change the value

$(myHtml).find('p[data-id="1"]').text("new text");

Also need to consider changing src of an image like

<img src="image.jpg" />

So I need something like

$(myHtml).find('img').attr("src", "new-image.jpg");

Thanks in advance

1 Answer 1

8

You need to wrap myHtml with $ for applying jQuery code

$(myHtml).find('p[data-id="1"]').text("new text");

To get that updated value use following method,

var myHtml = '<div>' +
  '<p data-id="1">A</p>' +
  '<p data-id="2">B</p>' +
  '<p data-id="3">C</p>' +
  '</div>';
myHtml = $(myHtml).find('p[data-id="1"]').text("new text").end()[0].outerHTML;
alert(myHtml);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div></div>

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

6 Comments

I tried that, it doesn't work when html was saved in a variable.
Thank you for reply. I'm still finding a solution.
@EdiboyIlagan myHtml=$(myHtml).find('p[data-id="1"]').text("new text").end()[0].outerHTML; alert(myHtml);
It's a great answer, but it would be much better if you explained what does end() does. Thanks so much anyway.
@PranavCBalan I knew that, but I think explaining it will be a good addition to your answer, thanks
|

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.