Jquery Replacewith() For Html String
Solution 1:
You are creating an dom structure and is modifying that dom structure, which won't modify the original string
To get the updated html, you need to get the updated content of the dom structure.
var $tmp = $('<div />', {
html: content
})
$tmp.find('.feature-box').each(function () {
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
var shortcode = '[feature' + attr + ']' + content + '[/feature]';
$this.replaceWith(shortcode);
});
var replaced = $tmp.html()
console.log(replaced);
Demo: Fiddle
Solution 2:
You don't actually assign the updated html anywhere. $this.replaceWith(shortCode);
updates $this
not content
.
You can use .html()
to get the updated content and assign it back.
content = $this.replaceWith(shortcode).html();
Due to the asynchronous nature of the jQuery each method, it runs a callback, you should also have the console.log
within the each function.
jQuery(content).filter('.feature-box').each(function(){
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
var shortcode = '[feature' + attr + ']' + content + '[/feature]';
content = $this.replaceWith(shortcode).html();
console.log(content);
});
Solution 3:
Strings are immutable objects in JavaScript, so you need to overwrite it with another value:
content = jQuery('<div>', {html: content})
.find('.feature-box')
.replaceWith(function() {
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
return'[feature' + attr + ']' + content + '[/feature]';
})
.end()
.html();
This also uses .replaceWith(fn)
syntax as a handy shortcut for .each()
and using .replaceWith()
inside.
Post a Comment for "Jquery Replacewith() For Html String"