0

I am developing a Chrome extension to manipulate a web page that I do not have control over, so I can't edit the existing css classes and html code. Based on the following example, I am trying to insert text in between two words within a paragraph:

<p class="abc">
<b>Title:</b>The Second Title
<br>
<b>Author:</b>Mary White
<br>
<b>Date:</b>2004
</p>
<p class="abc">
<b>Title:</b>The First Title
<br>
<b>Author:</b>John Smith
<br>
<b>Date:</b>2003
</p>

I have a list of names like:

Mary White -> Mary B. White

John Smith -> John L. Smith

I need to replace the first and last name with the full name ie: John Smith -> John L. Smith

I tried the following:

$(".abc:contains('Mary White')").text(function () {
  return $(this).text().replace("Mary White", "Mary B. White");
});

but that removes the <b> and <br> html tags.

I also tried this:

$(".htp:contains('John Smith')").replaceWith("John L. Smith");

but that replaces the entire p and replaces it with the full name. How can I get it to display the paragraph with the name containing the middle initial?

Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
abalone
  • 319
  • 2
  • 4
  • 13
  • It's not directly what you are looking at, but this is close http://stackoverflow.com/questions/2349138/jquery-find-and-replace-text-without-element-id – Brian Hoover Oct 17 '12 at 23:21

2 Answers2

3

Because text() removes the tags and just gives you the text.

Use .html(), but your code will fail if there is any html markup in the name.

epascarello
  • 204,599
  • 20
  • 195
  • 236
1

This is might be what you want:

$(function() {
    $(".abc").each(function(idx, elm) {
        elm.innerHTML = elm.innerHTML.replace("Mary White", "Mary B. White");
    });
});​

jsfiddle link

Jimmy Sawczuk
  • 13,488
  • 7
  • 46
  • 60
Neverever
  • 15,890
  • 3
  • 32
  • 50