如何将由<br/> <br/>分开的文本节点用自己的<p>标签包装?</p>

时间:2012-08-07 19:38:42

标签: javascript jquery html web-services

我的内容从我无法修改的网络服务返回,返回数据,如:

<div id="entrance" style="">
    Habilitação / Diploma de Ensino Medio Diploma de Ensino Pre Universitario 
    <br>
    <br>
    Diploma Record of study 
</div>

如何将两个句子分开包装? p>使用jQuery的标签?我知道我可以使用.wrap,但这会包装整个内容。我需要RegEx吗?

谢谢, 托马斯

更新:

我的要求改为需要列表而不是段落,所以使用下面的答案,我稍微修改它以包装&lt; li>然后整个事情在&lt; ul&gt;

jQuery('#entrance').show();
jQuery('#entrance').html(data).contents().each(function () {
if ( this.nodeType === 3 ) jQuery( this ).wrap( '<li />' );
    else jQuery( this ).remove();
});
jQuery('#entrance').wrapInner('<ul />');

2 个答案:

答案 0 :(得分:4)

怎么样:

$( '#entrance' ).contents().each(function () {
    if ( this.nodeType === 3 && $.trim( this.data ) !== '' ) {
        $( this ).wrap( '<p />' );
    } else {
        $( this ).remove();
    }
});

现场演示: http://jsfiddle.net/ZMD6m/5/

我的代码将所有非空文本节点转换为包含该文本的段落。删除所有其他类型的节点。

答案 1 :(得分:1)

此方法使用$(this).text()来查找每个子元素的长度。如果它为零,则将其删除,否则将其包含在段落中:

$('#entrance').contents().each(function(i,el) {
    if ($.trim($(this).text()).length) {
        $(this).wrap('<p>');
    } else {
        $(this).remove();
    }
});​

http://jsfiddle.net/mblase75/ZMD6m/3/