开发者

JQuery - How to convert html with br's in it to html with p's in it?

On the my page I have html like this:

hi<br>bye<br>sigh<br>hello <em>tie</em><br>lie 

with jquery, how can I convert it to html like this (basically using p's instead of br's):

<p>hi</p><p>bye</p><p>sigh</p><p>hello <em>tie</em></p><p>lie</p> 

My first attempt at doing this was this code:

$(container).contents().filter(function() {
                var val = this.nodeValue;
                return this.nodeType == TEXT_NODE && $.trim(开发者_如何学JAVAval).length > 0;
            })
            .wrap('<p></p>')
            .end()
            .filter('br')
            .remove();

This worked for the most part, except that hello and <em>tie</em> would not be in the same p element.

Does anyone know how I can do this properly?


simple javascript solution

var obj = document.getElementById('container'),
    str = obj.innerHTML,
    ar = str.split('<br />'),
    result = "";
for(var i = 0; i < ar.length; i++)
{
 result += '<p>' + ar[i] + '</p>';
}
obj.innerHTML = result;

I don't know how to do this with jQuery...


You were along the right lines, only there's not a convenient way(*) to wrap a range of children rather than just one at a time. You'd have to do it yourself, eg.:

// Take a range of children in a parent element and wrap them in a new element.
//
function wrapChildren(tagname, parent, child0, child1) {
    var wrapper= document.createElement(tagname);
    for (var i= child1-child0; i-->0;)
        wrapper.appendChild(parent.childNodes[child0]);
    parent.insertBefore(wrapper, parent.childNodes[child0]);
}

// Find `<br>`s and wrap the stretches between them.
//
var container= document.getElementById('container');
var lastbr= container.childNodes.length;
for (var i= lastbr; i-->0;) {
    var child= container.childNodes[i];
    if (child.nodeType===1 && child.tagName.toLowerCase()==='br') {
        wrapChildren('p', container, i+1, lastbr);
        container.removeChild(child);
        lastbr= i;
    }
}
wrapChildren('p', container, 0, lastbr);

(*: jQuery or otherwise. Well, there is surroundContents in DOM Range, but support is poor.)


'<p>'+html.replace(/<br\s?\/?>/gi,'</p><p>')+'</p>'

never tested. but thats the idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜