开发者

js - using replace method to replace html element

开发者 https://www.devze.com 2022-12-30 10:07 出处:网络
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\">

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开发者_StackOverflow中文版 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?


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


document.getElementById('demo').firstElementChild.innerHTML =
  document.getElementById('demo').firstElementChild.innerHTML.replace(/text/, "<span>1234</span>");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号