views:

77

answers:

2

hi everyone! 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?

A: 
document.getElementById('demo').firstElementChild.innerHTML =
  document.getElementById('demo').firstElementChild.innerHTML.replace(/text/, "<span>1234</span>");
Delan Azabani
+1  A: 

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

Nick Craver
thanks you!. i'm done with you answer :).
Rueta
Hi Nick! html(function(i, h) - what does the "i" stand for?
ming yeow
@ming - It gets 2 arguments, the first is the index, the second is the current `.html()` value :)
Nick Craver
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 yeow
@ming - since jQuery 1.4+, yes *most* functions will accept a function like this.
Nick Craver