1

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 ?

1
  • You could remove the specific text node and replace it. Commented Oct 4, 2015 at 15:03

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

7 Comments

you are replacing the whole inner html, not the selected placeholder
Working, but others text or content become Deleted or removed. Please fix this.
regexp looks nice. i'm upvoting this.
@guest271314 Hi Serious problem: It replace only one [text], It should replace text to class all text of same dive, like: [text1] ... [text2] ... [text3] on same dive class. Please fix this.
@Aabira "Serious problem: It replace only one [text], It should replace text to class all text of same dive, like: [text1] ... [text2] ... [text3] on same dive class. Please fix this." ? Not certain interpret comment correctly ? [text1] ... [text2] ... [text3] not appear at html at Question ? Tried adding g flag to RegExp ? Can create jsfiddle jsfiddle.net to demonstrate ?
|
0

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

4 Comments

thank, but how to replace any text like [any-text] to class of html node?
second statement replaces your placeholder... you want it to be dynamic? elaborate your question please.
i mean when i put any text inside [ ], like [any text here] , text will be class of html node.
in this case, best solution would be using regular expressions to catch every patterns matching [ only alphabetical charachers and the dash sign ]. I suck at regexps, sorry :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.