Iterating through text in p tag kills all html that was in the p tag
I am using this jquery code to to look inside a
tag and replace the word image with a span tag wrapped around it. The problem is my code is killing any other html thats in the <p>
tag.
Here is my code
$('p').each(
function() {
var text = $(this).text();
var spanText = text.replace('image', '<span class="bText">image</span>');
$(this).html(spanText);
}
);
H开发者_JAVA技巧ere is html before its applied
<p>
I have an image.
<br>
There is a link <a target="_blank" href="https://mysite.com">mylink</a>
</p>
After jquery
<p>I have an <span class="bText">image</span>. There is a link mylink </p>
Use html()
[docs] instead:
var text = $(this).html();
text()
[docs], as the name suggests, only gets the text content, no HTML tags.
Further information:
If you pass a string to replace
[docs], only the first occurrence of that string will be replaced. If you want to replace all occurrences, you need a regular expression [docs] with the g
lobal flag.
Your code could be shortened to (requires jQuery 1.4):
$('p').html(function(i, html) {
return html.replace(/image/g, '<span class="bText">image</span>');
// or /\bimage\b/g if you e.g. don't want to match `preimage`
});
//mine from scratch - works in chrome, ie, and firefox
$("p").each(function(){
var html = $(this).html();
var newHtml = html.replace("image","<span style='font-weight:bold;'>image</span>");
$(this).html(newHtml);
});
//end
in your code change
var text = $(this).text();
for
var text = $(this).html();
hope this helps.
精彩评论