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?
Deduplicator
46k7 gold badges73 silver badges125 bronze badges
asked May 14, 2010 at 2:15
Rueta
3,6072 gold badges26 silver badges22 bronze badges
2 Answers 2
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);
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.
answered May 14, 2010 at 2:18
Nick Craver
631k138 gold badges1.3k silver badges1.2k bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
meow
Hi Nick! html(function(i, h) - what does the "i" stand for?
Nick Craver
@ming - It gets 2 arguments, the first is the index, the second is the current
.html() value :)meow
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?
Nick Craver
@ming - since jQuery 1.4+, yes most functions will accept a function like this.
document.getElementById('demo').firstElementChild.innerHTML =
document.getElementById('demo').firstElementChild.innerHTML.replace(/text/, "<span>1234</span>");
answered May 14, 2010 at 2:17
Delan Azabani
81.8k30 gold badges174 silver badges215 bronze badges
Comments
default