Replace any plain-text to class of specific div

2019-08-08 15:57发布

Trying to replace any plain-text like [make-this-class] to class like <div class='make-this-class'></div> of specific div <div class='this-div-only'></div>.

HTML:

<div class='not-others-div'>
text text [make-this-class] text
</div>
Text text text
<div class='this-div-only'> <!-- this div only -->
text text [make-this-class] text
</div>

How to replace any plain-text [any-text] to a class of specific div of dom elements by jquery ?

2条回答
冷血范
2楼-- · 2019-08-08 16:52

you store the content of your div, replace the string you're looking for and finally update your div's content with new content.

var content = $('.this-div-only').html();

var newcontent = content.replace('[make-this-class]', '<div class="make-this-class"></div>');

$('.this-div-only').html(newcontent);
查看更多
Viruses.
3楼-- · 2019-08-08 16:54

Try utilizing .html() , String.prototype.replace() with RegExp /\[(.*)\]/

$(".this-div-only").html(function(i, html) {
  return html.replace(/\[(.*)\]/, $("<div />", {"class":"$1"})[0].outerHTML)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class='not-others-div'>
text text [make-this-class] text
</div>
Text text text
<div class='this-div-only'> <!-- this div only -->
text text [make-this-class] text
</div>

查看更多
登录 后发表回答