For all jQuery experts,
looking for a clean way to remove a span, and insert with anoth block of code, which includes the original content. more specifically,What I have:
<span class="error">ORIGINAL TEXT</span>
Needs to replace with (error icon and formatting with jQueryUI. Unfortunately, I can't change the original text, so need it to achieve through script)
<div class="ui-widget">
<div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
<p&开发者_运维知识库gt;<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"> </span>
<strong>ORIGINAL TEXT</strong></p>
</div>
</div>
Ideally, the replacement should not affect the positioning. the original <span>
is inline with other elements, and not sure whether the will make it goes below. But, that is another issue.
First issue is that divs are display: block by default. You'll need to style ui-widget so that the div is inline.
<style>
.ui-widget { display: inline; }
</style>
Then, you'll need to replace the span with a new dom structure:
<script type="text/javascript">
var originalText = $("span.error").text();
$("span.error").replaceWith(
$("<div>").attr("class", "ui-widget")
.append($("<div>").attr("class", "ui-state-error ui-corner-all").attr("style", "padding: 0 .7em;")
.append($("p")
.append($("<span>").attr("class", "ui-icon ui-icon-alert").attr("style", "float: left; margin-right: .3em;"))
.append($("<strong>").text(originalText))
)
);
</script>
For performance and organizational reasons, I like to keep the markup in the HTML (instead of building big HTML strings in javascript), so I usually create hidden template nodes for this sort of thing. The jQuery function you want is replaceWith().
HTML:
<span class="error">ORIGINAL TEXT</span>
<span class="error">ORIGINAL TEXT2</span>
<div class="ui-widget" id="error-template" style="display:none;">
<div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"> </span>
<strong>ORIGINAL TEXT</strong></p>
</div>
</div>
SCRIPT:
$(document).ready(function() {
$('span.error').each(function(i,v) {
var text = $(this).text();
var newBlock = $('#error-template').clone().removeAttr('id').show();
newBlock.find('strong:first').text(text);
$(this).replaceWith(newBlock);
});
});
See it in action at jsfiddle.
精彩评论