Fizzix
Fizzix

Reputation: 24375

How to change tag types with jQuery

So I have a HTML editor (WYSIWYG editor) on my site that really isn't responding the way it should be.

Basically, it is loading all my sections within a fieldset wrapper, which is fantastic, but then it also creates all sections as a fieldset. I need to breakdown this section and convert it to a description list, dl.

Here is what it is currently like:

<fieldset>
    <legend>Our Services</legend>
    <fieldset>
        <legend>Some title here</legend>
        <p>Some long text here...</p>
        <p>Some long text here...</p>
    </fieldset>
    <fieldset>
        <legend>Some title here</legend>
        <p>Some long text here...</p>
        <p>Some long text here...</p>
    </fieldset>
    <fieldset>
        <legend>Some title here</legend>
        <p>Some long text here...</p>
        <p>Some long text here...</p>
    </fieldset>
    <fieldset>
        <legend>Some title here</legend>
        <p>Some long text here...</p>
        <p>Some long text here...</p>
    </fieldset>
</fieldset>

Here is what the converted version should be like:

<fieldset>
    <legend>Our Services</legend>
    <dl>
        <dt>Some title here</dt>
        <dd><p>Some long text here...<p></dd>

        <dt>Some title here</dt>
        <dd><p>Some long text here...<p></dd>

        <dt>Some title here</dt>
        <dd><p>Some long text here...<p></dd>

        <dt>Some title here</dt>
        <dd><p>Some long text here...<p></dd>
    </dl>
</fieldset>

I know I need to use functions like replaceWith and wrap, although I am just not to sure how to approach this.

The function that is created will be run when the document is ready and will convert everything that way. I no it is not ideal, but hey, it'll do.

I am not asking anyone to write me a huge chunk of code, I am mainly asking for guidance on how to approach this.

Upvotes: 0

Views: 49

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

As an ideal solution I would recommend fixing the root cause, ie the editor.

If that is not possible try

var $items = $('fieldset fieldset').wrap('<dl />').contents().unwrap().parent();
$items.find('legend').wrap('<dt />').contents().unwrap();
$items.each(function () {
    $(this).find('p').wrapAll('<dd />');
})

Demo: Fiddle, Or Fiddle

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

A solution for the specifically described problem is

var fieldset = $('fieldset fieldset');

fieldset.wrapAll('<dl>').find('legend').wrapInner('<dt>').children().unwrap()
fieldset.each(function(){
    $(this).find('p').wrapAll('<dd>');
}).children().unwrap();

Demo at http://jsfiddle.net/YD5n5/

Upvotes: 1

Related Questions