1

I was hoping to indent a number, but the with html generated from my cms I can't seem to hook into the number and apply a style.

<div class="content">
<b>01. Header</b>
Lorem ipsum dolor sit amet, consectetur 
adipisicing elit, anim odio hic autem 
delectus qui labore rerum irure autem 
</div>

I would like to wrap the number in a span. All of the content is the same. 02.[space]Title

<div class="content">
<span="indent">01. </span><b>Header</b>
Lorem ipsum dolor sit amet, consectetur 
adipisicing elit, anim odio hic autem 
delectus qui labore rerum irure autem 
</div>


.indent{
    margin-left: -30px;
}

Here is what I have started but I can't seem to trim it to the first 3 characters including the empty space.

 $('.content b').each(function() {
var tmp = [],
    collecting = false;

$(this).contents().each(function() {
    if (this.nodeType === Node.TEXT_NODE && $.trim(this.nodeValue).length > 0) {
        if (collecting) {
            tmp.push(this);
            return false;
        }
        else {
            collecting = true;
        }
    }

    if (collecting) {
        tmp.push(this);
    }
});

$(tmp).wrapAll('<span class="indent" />');
});​

http://jsfiddle.net/hGeuZ/

uriah
  • 2,485
  • 5
  • 28
  • 40

4 Answers4

0

You can try this way

$('.content b').each(function () {
   var txtArr = $(this).text().split(' ');

    $(this).before('<span class="indent">'+txtArr [0]+'</span>')

    txtArr.shift()
    $(this).text(txtArr.join(' '))

});

Here is the demo, http://jsfiddle.net/hGeuZ/19/

Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70
0

This is not the most orthodox solution but it might suit your needs:

$('.content b').each(function () {
    var result = $(this).text().replace(/([0-9]+\.)/, '<span class="indent">$1</span>');
    $(this).html(result).find('.indent').remove().insertBefore(this);
});​

http://jsfiddle.net/hGeuZ/10/

Petah
  • 45,477
  • 28
  • 157
  • 213
0
$("b").each(function() {
   var $title = $(this).html();
   var spaceIndex = $title.indexOf(" ");
   var num = $title.substring(0, spaceIndex+1);
   var text = $title.substring(spaceIndex+1, $title.length)
   console.log(num+text);
   num = '<span class="indent">'+ num + '</span>';
   $(this).html(num + text);   

});
Manu
  • 609
  • 8
  • 18
0

For this, one approach I'd suggest is:

$('.content b:first-child').replaceWith(
    function(i,h){
        return h.replace(/(\d+.\s)([\d\D]*)/g,'<span class="indent">$1</span><b>$2</b>');
    });​

JS Fiddle demo.

If CSS is an option:

.content {
    counter-increment: headerNumber;
}

.content b:first-child::before {
    content: counter(headerNumber, decimal-leading-zero);
    padding-right: 2em;
    color: #f90;
}​

JS Fiddle demo.

David Thomas
  • 249,100
  • 51
  • 377
  • 410