简体   繁体   中英

jQuery .append() after offset

I have this:

<div id="testcase">abcdefghijklmnopqrstuvwxyz</div>

I would like to add this: <span> with an offset.

So when I for example would have the JS function: addSpan(4) this would happen:
<div id="testcase">abcd<span>efghijklmnopqrstuvwxyz</div>

To visualise what I'm looking for:

function addSpan(i){
    $('#testcase').append('<span>', i);
}

Use slice and concatinate...

function addSpan(i){
    var content = $("#testcase").html();
    var before = content.slice(0, i);
    var after = content.slice(i + 1);
    $("#testcase").html(before + "<span></span>" + after);
}

Here another wut i tired LIVE DEMO

$("#btn_clck").on('click', function () {
    var gText = $("#testcase").html();
    var getlength = gText.length;
    var finalValue = "";

    for (var i = 0; i < getlength; i++) {
        var setData = gText.charAt(i);
        if (i == 4) {
            finalValue += '<span></span>'
        }
        finalValue += setData;
    }
    $("#testcase").text(finalValue);
});

but i think Steini's answers was better

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