I want to replace following HTML string:
</p><span onclick="alert(event)" class="btn btn-sm btn-success" contenteditable="false">XXX</span><p><br></p>
with:
</p><button onclick="alert(event)" class="btn btn-sm btn-success" contenteditable="false">YYY</button><p><br></p>
using jQuery. I have tried .replace()
function, but its not working for some strange reason.
try give span an ID and
You can do:
$("#yourid").text("YYY");
or
$("#yourID").html("testing <b>YYY</b>");
Try this, but better to add an ID for selector.
$(document).ready(function(){
$('span').click(function(){
$(this).text('YYY') or $(this).html('YYY');
})
})
Here you go with a solution https://jsfiddle.net/bqfv5fge/1/
var span = $('span:contains("XXX")'); span.after('<button>YYY</button>'); $(span[0].attributes).each(function() { $('button:contains("YYY")').prop(this.nodeName, this.nodeValue); }); span.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span onclick="alert(event)" class="btn btn-sm btn-success" contenteditable="false">XXX</span><p> test paragraph </p>
Use jQuery
contains
to get the target element.
Reference Document: https://api.jquery.com/contains-selector/
First get the reference of span
element, then add button
next to span using jQuery
after
.
Then attach all the attribute
to the button
and then remove span
.
var attr =''; $("span").each(function(){ $.each(this.attributes,function(){ attr += this.name+'="'+this.value+'"'; }); }); $("span").replaceWith('<button '+attr+'>'+$('span').text()+'</button>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span onclick="alert(event)" class="btn btn-sm btn-success xyz" contenteditable="false">XXX</span>
If you just want to replace "span" with "button" tag:
$(document).ready(function(){
var x = '</p><span onclick="alert(event)" class="btn btn-sm btn-success" contenteditable="false">XXX</span><p><br></p>';
alert(x.replace(/span/g,"button"));
});
https://jsfiddle.net/L26fvfvL/
If you want to replace XXX with YYY:
HTML Code:
<span onclick="alert(event)" class="btn btn-sm btn-success" contenteditable="false">XXX</span>
JQuery Code:
$(document).ready(function(){
var x = $("span");
x.html(x.html().replace("XXX","YYY"));
})
https://jsfiddle.net/f7qsa6kw/
If you want to do both the things, apply the second step and then first step.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.