最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery - wrap all unwrapped text in p tags - Stack Overflow

programmeradmin3浏览0评论

I have a situation where the following code is getting written to my page.

<div>
    Some text here which is not wrapped in tags
    <p>Some more text which is fine</p>
    <p>Blah blah another good line</p>
</div>

In this case it always seems to be the first line which is not being wrapped in p tags which might make the solution to this easier, although it's not every time. Some times it is fine.

What I need to do is identify whether the first line is wrapped or not and if not then wrap it.

Unfortunately I'm not sure where to start with this problem so any help would be appreciated.

I have a situation where the following code is getting written to my page.

<div>
    Some text here which is not wrapped in tags
    <p>Some more text which is fine</p>
    <p>Blah blah another good line</p>
</div>

In this case it always seems to be the first line which is not being wrapped in p tags which might make the solution to this easier, although it's not every time. Some times it is fine.

What I need to do is identify whether the first line is wrapped or not and if not then wrap it.

Unfortunately I'm not sure where to start with this problem so any help would be appreciated.

Share Improve this question asked Dec 12, 2012 at 9:29 TomTom 13k50 gold badges153 silver badges247 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

Try using this code to wrap any TextNodes that are not wrapped with <p> tag.

function getTextNodesIn(node, includeWhitespaceNodes) {
    var textNodes = [], whitespace = /^\s*$/;

    function getTextNodes(node) {
        if (node.nodeType == 3) {
            if (includeWhitespaceNodes || !whitespace.test(node.nodeValue)) {
                textNodes.push(node);
            }
        } else {
            for (var i = 0, len = node.childNodes.length; i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }

    getTextNodes(node);
    return textNodes;
    }

    var textnodes = getTextNodesIn($("#demo")[0])​​​​;
    for(var i=0; i < textnodes.length; i++){
        if($(textnodes[i]).parent().is("#demo")){
            $(textnodes[i]).wrap("<p>");
        }
    }​

here is a jsfiddle that shows this in action.

PS: TextNode detection part has been borrowed from this answer

here you go: http://jsfiddle/RNt6A/

$('div').wrapInner('<p></p>');​​​​
$('div p > p').detach().insertAfter('div p');

Try this :-

<div class="container">
Some text here which is not wrapped in tags
<p>Some more text which is fine</p>
<p>Blah blah another good line</p>
</div>​

JS

    $(function(){
    var $temp = $('<div>');
    $('div.container p').each(function(){
            $(this).appendTo($temp);            
    });     

    if($.trim( $('div.container').html() ).length){
       var $pTag = $('<p>').html($('.container').html()); 
        $('div.container').html($pTag);
    }

    $('div.container').append($temp.html());
});
​

​Here is the working example :-

http://jsfiddle/dhMSN/12

Ran into a similar need and attempted to employ the solution @Arash_Milani. Solution worked, however I ran into conflicts when the page also required to make ajax calls.

After a bit of digging, I found a fairly straight-forward solution on api.jquery. using the .contents() method:

$('.wrapper').contents().filter(function() {
  return this.nodeType === 3;
}).wrap('<p class="fixed"></p>').end();
p.good {
  color: #09f;
}
p.fixed {
  color: #ff0000;
  text-align: center;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
  Some plain text not wrapped in any html element.
  <p class="good">This text is properly wrapped in a paragraph element.</p>
</div>

jQuery is bad at handling text nodes, so you'll need to do some direct DOM manipulation on this. This also uses the "trim" function.. Its on jsfiddle.

var d = $("div")[0];

for(var i=0; i<d.childNodes.length; i++) {
    if(d.childNodes[i].nodeType === 3 &&
       d.childNodes[i].textContent.replace(/^\s+|\s+$/g, "")) {
        wrapNode(d.childNodes[i]);
    }
}

function wrapNode(node) {
    $(node).replaceWith("<h1>" + node.textContent + "</h1>");
}
发布评论

评论列表(0)

  1. 暂无评论