0

I have a question. I have a work this morning but i don't know how to do it. My work here (html):

<div class="demo">
    <p>this is demo text</p>
</div>

Here is my JS:

var tempdata = $(".demo").text();
var replacedata = tempdata.replace("text","<span>1234</span>");

Look everything ok. But result is: this is demo <span>1234</span>. This isn't my result I want. How to make in this string become a HTMLelement by using replace method?

2 Answers 2

1

When assigning the value back, use .html() instead of .text() so it won't encode it, like this:

var tempdata = $(".demo").text();
var replacedata = tempdata.replace("text","<span>1234</span>");
$(".demo").html(replacedata);​​​​​​

You can see a demo here

Also, you can pass a method to .html() if you're doing this to many elements, like this:

$(".demo").html(function(i, h) {
    return h.replace("text","<span>1234</span>");
});​

Note this uses .html() as the source as well, but makes no difference for the example code.

You can see a demo of that here

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

4 Comments

Hi Nick! html(function(i, h) - what does the "i" stand for?
@ming - It gets 2 arguments, the first is the index, the second is the current .html() value :)
I see! I tried: $("textarea").html(function(i,h){console.log(h)}). I see it iterates through all the elements, allowing me to apply for function for it. thanks a tonne for helping me understand this. Can i use this technique for all functions?
@ming - since jQuery 1.4+, yes most functions will accept a function like this.
1
document.getElementById('demo').firstElementChild.innerHTML =
  document.getElementById('demo').firstElementChild.innerHTML.replace(/text/, "<span>1234</span>");

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.