0

I'm creating a counter by passing a number to following function:

function numberToHtml(n) {
            function createSpan(n) {
                var span = document.createElement('span');
                span.textContent = n;
                return span;
            }
            function iter(n, container) {
                if (n === '') return container;
                container.insertBefore(createSpan(n.slice(-3)), container.firstChild);
                return iter(n.slice(0,-3), container);
            }
            return iter(String(n), document.createDocumentFragment());
        }

This returns:

DocumentFragment [ <span>, <span> ]

I'm havibng trouble to get a number of elements in the DocumentFragment. I tried $(myobject).length, which returns 1.

How can I get the no of items in my DocumentFragment?

user1049961
  • 2,656
  • 9
  • 37
  • 69

2 Answers2

2
var me = numberToHtml(123455);
alert( me.childElementCount);

alerts 2 NOTE: also me.children.length returns 2

To see what you have to work with do this:

console.dir(me);

then expand that in the console.

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
1

Sorry my first answer wasn't correct. I had trouble figuring out, how you got your outcome (that would have been helpfull). What you are looking for is:

var myobject = numberToHtml(3231123123);
var length = $(myobject).children().length;
alert(length); // 4

or as juhana pointed out, you can omit the jquery wrapper:

var myobject = numberToHtml(3231123123);
var length = myobject.children.length;
alert(length); // 4

Since the span elements are added as children, you want to count the children of the container.

Le 'nton
  • 366
  • 3
  • 22