简体   繁体   中英

Wrap text with <span> element using Javascript or jQuery

I have the following HTML code on my page. There is no containing element, it's just in the body .

<b>SqFt per Carton: </b>24.30<br>

Using script, I want to wrap 24.30 in a span tag with a class so the result will look like this:

<b>SqFt per Carton: </b><span class="sqft_cart">24.30</span><br>

How can I do this?

Here is jQuery way to achieve what you asked for by iterating over all text nodes (ie text without any tag) in the document, and in case they come right after <b> tag replace them with <span> having proper class:

$(document).ready(function() {
    $("body").contents().filter(textNodeFilter).each(function(index) {
        var textNode = $(this);
        if (this.previousSibling && this.previousSibling.tagName.toLowerCase() === "b") {
            var value = textNode.text();
            var oSpan = $("<span>").html(value).addClass("sqft_cart");
            textNode.replaceWith(oSpan);
        }
    });
});

function textNodeFilter() {
    return this.nodeType == 3;
}

Live test case .

$("b").parent().contents().filter(function() {
    return this.nodeType != 1;
}).wrap("<span class='sqft_cart'></span>");

http://jsfiddle.net/FW8Ct/4/

you could get the value of SqFt per Carton: 24.30 by using

var takentext = $("class Or ID of SqFt per Carton").text();
$("class of span").text(takentext);

Since you don't have a containing element you can use .nextSibling() to get the text node for 24.30 . Then .insertAdjacentHTML() inserts the new span after deleting the old text node. Since I don't know what the rest of your page looks like, I'll assume there could be multiple <b> elements, but the code will work either way.

Demo: http://jsfiddle.net/ThinkingStiff/6ArzV/

Script:

var bs = document.getElementsByTagName( 'b' );

for( var index = 0; index < bs.length; index++ ) {

    if( bs[index].innerHTML.indexOf( 'SqFt per Carton:' ) > -1 ) {
        var text = bs[index].nextSibling,
            span = '<span class="sqft_cart">' + text.nodeValue + '</span>';
        text.parentNode.removeChild( text );
        bs[index].insertAdjacentHTML('afterEnd', span);
    };

};

HTML:

<b>SqFt per Carton: </b>24.30<br>
<b>Price per Carton: </b>193.00<br>
<b>SqFt per Carton: </b>12.90<br>
<b>Price per Carton: </b>147.00<br>
<b>SqFt per Carton: </b>14<br>

CSS:

.sqft_cart {
    color: red;
}

Output:

在此输入图像描述

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