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 ?
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>
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);