Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jquery to convert divs into spans

Tags:

html

jquery

I am trying to alter the HTML output of a widget I have no control over. Basically the issue is that the widget outputs HTML that uses divs inside of a p which is not valid..

<div class="widget_output">
    <ul>
        <li>
            <p>
                <div>This is a random item</div>
                <div>This is a random item</div>
                <div>This is a random item</div>
                <div>This is a random item</div>
            </p>
       </li>
       <li>
            <p>
                <div>This is a random item</div>
                <div>This is a random item</div>
                <div>This is a random item</div>
                <div>This is a random item</div>
            </p>
        </li>
</div>

My idea is to change the divs into spans which are inline elements, the HTML should then be valid. I have been looking at jquery to try and select the class and then convert these divs into spans. Can anyone point me in the right direction or a tutorial of someone achieving something similar?

like image 941
fightstarr20 Avatar asked Jul 29 '12 07:07

fightstarr20


People also ask

Can you put divs in a span?

The phrasing elements can only contain other phrasing elements, for example, you can't put div inside span.

Are div and SPAN tags interchangeable?

Divs and spans are not interchangeable in web page building.

What is the difference between span and div subjective?

The difference between span and div is that a span element is in-line and usually used for a small chunk of in-line HTML whereas a div (division) element is block-line (which is basically equivalent to having a line-break before and after it) and used to group larger chunks of code. Save this answer.


1 Answers

Just stuck a JSFiddle together:

http://jsfiddle.net/daYL4/3/

$(".widget_output div").replaceWith(function() { 
    return "<span>" + this.innerHTML + "</span>"; 
});

Seems to work better than my original suggestion. ​ But take a look at the answers to this related question, as they cover some good points:

Use jQuery to change an HTML tag?

like image 98
Spikeh Avatar answered Sep 21 '22 18:09

Spikeh