使用jquery将div转换为跨度 [英] Use jquery to convert divs into spans
问题描述
我试图改变我无法控制的小部件的HTML输出。基本上,问题是widget会输出HTML中使用div的内容,这是无效的。
< div class = widget_output >
< ul>
< li>
< p>
< div>这是一个随机项目< / div>
< div>这是一个随机项目< / div>
< div>这是一个随机项目< / div>
< div>这是一个随机项目< / div>
< / p>
< / li>
< li>
< p>
< div>这是一个随机项目< / div>
< div>这是一个随机项目< / div>
< div>这是一个随机项目< / div>
< div>这是一个随机项目< / div>
< / p>
< / li>
< / div>
我的想法是将div转换为内联元素的跨度,然后HTML应该是有效的。我一直在寻找jQuery来尝试选择类,然后将这些div转换为跨度。任何人都可以指向我正确的方向或某人获得类似的教程? 你不需要jQuery,您可以简单地使用正则表达式将< div>
标签替换为< span>
标签。试试这个:
var widgetHTML = $('div.widget_output')。html();
widgetHTML = widgetHTML
.replace(/< div> / g,'< span>')
.replace(/< \ / div> / g,'< /跨度>');
$('div.widget_output')。html(widgetHTML);
演示: http://jsfiddle.net/codef0rmer/daYL4/3/
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?
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/
这篇关于使用jquery将div转换为跨度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!