简体   繁体   中英

How can I wrap a <span> around the first character in an object with jQuery

I've been able to find and console.log the first characters that meet my criteria. I am trying to wrap a <span> tag around the characters but keep running into trouble. This is what I have so far.

$(document).ready(function () {
 $('.drop-cap').each(function(i,obj) {
  $(this).find("p").text().charAt(0).append("<span class='dropcap'>");
 })
});

Use can use the substring function to get part of a string which will allow you to separate the start from the end.

$(document).ready(function () {
    $('.drop-cap').each(function(i,obj) {
        var $p   = $(this).find("p"),
            text = $p.text();
        
        if(text.length === 0){
            // no text to be wrapped
            return;
        }

        $p.html('<span class="dropcap">' + text[0] + '</span>' + text.substring(1));
    })
});

ES6

$(document)
  .ready(() => {
      $('.drop-cap')
        .each((index, element) => {
            let $p   = $(element).find("p"),
                text = $p.text();
        
            if(text.length === 0){
                // no text to be wrapped
                return;
            }

            $p.html(`<span class="dropcap">${text[0]}</span>${text.substring(1)}`);
        });
  });

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