Replace the wrapper with a single letter span with jquery

I need to replace the first letter in the content div and wrap it with a tag <span>.

Here is my html:

<div class="first_ltr">
    <p>This is a Test </p>
</div>

I want to replace html as:

<div class="first_ltr">
    <p><span>T</span>his is a Test </p>
</div>

I tried:

$(".first_ltr").each(function () {
    var currentText = $(this).html();
    $(this).text(currentText.replace("0","<span></span>"));
});

Can anyone help? Thank you in advance.

+5
source share
7 answers

You can go to . html callback and add any tag to text e.g.

$('.first_ltr p').html(function (index, html) {
  return '<span>' + html.slice(0, 1) + '</span>' + html.slice(1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first_ltr">
  <p>This is a Test </p>
</div>
Run codeHide result

html.slice(0, 1) - returns the first letter in a string

html.slice(1) - returns a string without the first letter

Update I wrote a small plugin, you can try it

$.fn.wrapText = function (tag, position) {
    var $contaiter = $('<div />');

    this.html(function (index, html) {
        var start = position;
            end   = position + 1;

        if (position > html.length) {
            position = 0;
        }

        $contaiter.html($('<' + tag + '/>').html(html.slice(start, end)));

        return [html.slice(0, start), $contaiter.html(), html.slice(end)].join('');
    });
};

$('.first_ltr p').wrapText('span', 0);
$('.last_ltr p').wrapText('div', 13);

Example

+8
source

check the code below. check out demo

First option

 $(".first_ltr").each(function () {
    var currentText = $.trim($(this).text());
    var firstChar = currentText.charAt(0);
    currentText = currentText.substring(1, currentText.length);
   $(this).find('p').html('<span>'+firstChar+'</span>'+currentText);
 });

, slice DEMO

  $(".first_ltr").each(function () {
     var currentText = $.trim($(this).text()); 
     $(this).find('p').html('<span>'+currentText.slice(0,1)+'</span>'+currentText.slice(1));
  });
+1

, :

var $span = $('<span />');
$(".first_ltr > p").each(function(){
    var firstLetter = $(this).text().slice(0,1); //find first letter
    var text = $(this).text().slice(1); //find rest of the text 
    $span.text(firstLetter); //wrap first letter in span-tag
    $(this).text(text); //override old text
    $(this).prepend($span); //prepend first letter
});

+1

- .

var text = $('.first_ltr p').text();
var split = text.split('');
var firstLetter = split[0];
var rest = split.splice(1,split.length)
$('.first_ltr p').html('<span>' + firstLetter +'</span>' + rest.join(''));

https://jsfiddle.net/d1pf6cjy/1/

+1

:

$(document).ready(function(){
    var myText = $('.first_ltr > p').text();
    var start = '<span>' + myText.slice(0,1) + '</span>';
    var end = myText.slice(1, myText.length);
    $('.first_ltr > p').html(start + end);
});

: http://jsfiddle.net/r2zp2vqm/1/

, !

+1

JavaScript. , , , OP.

JSFiddle , , . , .

DOM API DOM . , , . , , . , HTML, .

. , , , ([a-zA-Z]+), ..

var wrapFirst = function(nodes, letters) {
    var rgx = new RegExp("^([\\s\\S]*?)(" + letters + ")");
    
    for (var i = 0; i < nodes.length; ++i) {
        // 1) Find the first text node
        var root = nodes[i];
        var n = root.firstChild;
        var txt;
        
        while (n) {
            // Text node?
            if (n.nodeType == Node.TEXT_NODE) {
                if ((txt = n.data.match(rgx))) {
                    break;
                }
            // Non-text node with children?
            } else if (n.firstChild) {
                n = n.firstChild;
                continue;
            }
            
            // Has next sibling?
            if (n.nextSibling) {
                n = n.nextSibling;
            // Parent has next sibling?
            } else if (n.parentNode !== root) {
                n = n.parentNode.nextSibling;
            // Nothing useful found
            } else {
                n = undefined;
            }
        }
        
        // 2) Wrap the text
        if (n) {
            // Remove char from the old text
            n.data = n.data.substring(txt[0].length);
            
            // Add the span (+prefix if any)
            var p = n.parentNode;
            if (txt[1]) {
                p.insertBefore(document.createTextNode(txt[1]), n);
            }
            var wr = document.createElement("span");
            wr.appendChild(document.createTextNode(txt[2]));
            p.insertBefore(wr, n);
        }
    }
}

wrapFirst(
    document.getElementsByClassName("first_ltr"),
    "[a-zA-Z]"
);
span { background: yellow; }
<div class="first_ltr">
  <p>This is a Test </p>
</div>
Hide result

For the version that uses jQuery, you can see the previous version of this answer (at the bottom, not the broken code at the top). This gives the same result, but may be slightly less efficient (due to jQuery, but also because of the need to do more general regex checks).

-1
source

Use this:

Prepare jQuery Method

$( ".first_ltr" ).prepend( "<span>T</span>" );

Click here for more information.

-4
source

All Articles