简体   繁体   中英

How do I wrap each text item in a tag with another tag, like p

So, before you ask why, the idea is to find the position of the text on the screen, the only way I've found to do that is it's an actual element.

$('button#orphan').click(function(){

    //The vars are defined globally for debugging.

    pNodeSplitText = new Array();
    pNodes=$('p');
    orphanedNodes=new Array();
    pNodes.each(function(index){
        pNodesHTMLbefore=pNodes.eq(index).html(); //May not be nessicary
        pNodeSplitText[index] = pNodes.eq(index).text().split(' '); //To get each text item
        pNodeSplitText.each(function(i){
          // this is where i will wrap each wrord, but how?
        })
    })
})

You didn't provide any HTML but if it's just like given (in the example here) HTML then you may try something like this ( Example )

HTML:

<p>Some text</p>
<p>Some more text</p>

JS:

$('button#orphan').click(function(){
    var pNodeSplitText = [], orphanedNodes = [], pNodes = $('p');
    pNodes.each(function(i){
        pNodeSplitText = pNodes.eq(i).text().split(' ');
        var newText = '<span class="txt">' + pNodeSplitText.join('</span> <span class="txt">') + '</span>';
        $(pNodes[i]).html(newText);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM