1

How to change:

<p class="myClass">Lorem Ipsum (and maybe other nested tags)</p>

into:

<code class="myClass">Lorem Ipsum (and maybe other nested tags)</code>

?

This is an offline job. It's just an update but there are thousands of ps that I need to change into codes.

4
  • 1
    Are you saying you want to permanently update your source html? Most IDEs will let you do a find and replace across all the files in a project, as will tools like Notepadd++. Commented Mar 20, 2012 at 11:44
  • 1
    Why do you need or plan to make these changes on line or even off line at the client side ..? Commented Mar 20, 2012 at 11:49
  • @nnnnnn Yes, it's a permanent update. Find-replace will find <p class="myClass"> and replace it with <code class="myClass">; but what about the ending </p> (obviously there are ending paragraphs that do't correspond to <p class="myClass">. Commented Mar 20, 2012 at 11:54
  • @hornetbzz It's a bug in iBooks that I need to overcome (the Html files will be the source for the ePubs). Commented Mar 20, 2012 at 11:56

1 Answer 1

4

You can use contents() to obtain the element's children (including text nodes), then combine unwrap() and wrapAll():

$("p.myClass").contents().unwrap().wrapAll("<code class='myClass'></code>");

Update: If you have more than one <p> element, you have to iterate over them with each() to avoid reparenting all of them inside a single <code> element:

$("p.myClass").each(function() {
    $(this).contents().unwrap().wrapAll("<code class='myClass'></code>");
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. I'm not familiar with Jquery; I've just tried $(document).ready(function() { $("p.code").contents().unwrap().wrapAll("<code class='code'></code>"); }); but what it does is that it puts the text from all <p class="myClass">s into one single <code class="myClass">. In other words, it replaces the first occurrence of <p class="myClass"> ... </p> with <code class="myClass"> (the contents of all <p>s that have a class="myClass") </class>.
Yup, that will indeed happen if you have several <p> elements. The solution is to iterate over them, see my updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.