Skip to content Skip to sidebar Skip to footer

Use Jquery To Convert Divs Into Spans

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.. <

Solution 1:

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?

Solution 2:

You do not need jQuery for that, you can simply use regular expression to replace <div> tags with <span> tags. Try this:

var widgetHTML = $('div.widget_output').html();
    widgetHTML = widgetHTML
       .replace(/<div>/g, '<span>')
       .replace(/<\/div>/g, '</span>');
$('div.widget_output').html(widgetHTML);

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

Post a Comment for "Use Jquery To Convert Divs Into Spans"