extempl
extempl

Reputation: 3137

get SINGLE text node from DOM object

Need to get all direct nodes from DOM element and don't actually know, how it many and what kind they are. .contents()? Ok, let's see..

$('<div />').html('<p>p</p>').contents() -> [<p>​p​</p>​]

Ok.

$('<div />').html('textNode').contents() -> []

WTF?

$('<div />').html('textNode').append('another').contents() -> ["textNode", "another"]

Ok, so what about single text node?

Upvotes: 1

Views: 909

Answers (2)

rlemon
rlemon

Reputation: 17666

I don't know if this is helpful. A while ago I built a Document Fragment generator using JSON styled input. I also wrote a (somewhat working) reverse function for it so you could turn your nodeList into a JSON string.

https://gist.github.com/2313580

var reverseFunction = function(DOM /* DOM tree or nodeList */) {
    var tree = [];[].forEach.call(DOM, function(obj) {
        if (obj instanceof Text) {
            tree.push({
                'textContent': obj.textContent
            });
        } else {
            var tmp = {};
            tmp['tagName'] = obj.nodeName;
            for( var data in obj.dataset ) {
                tmp['data-' + data] = obj.dataset[data];
            }
            for (var i = 0, l = obj.attributes.length; i < l; i++) {
                var key = obj.attributes[i].name,
                    val;
                if (key.indexOf('data-') === -1) {
                    switch (key) {
                    case ('class'):
                        key = 'className';
                        break;
                    case ('style'):
                        val = {};
                        obj.attributes[i].value.split(';').forEach(function(rule) {
                            var parts = rule.split(':');
                            val[parts[0]] = parts[1];
                        });
                        break;
                    };
                    tmp[key] = val || obj.attributes[i].value;
                }
            }
            if (obj.childNodes.length > 0) {
                tmp['childNodes'] = reverseFunction(obj.childNodes);
            }
            tree.push(tmp);
        }
    });
    return tree;
};

This does find textNodes and separates them... You may be able to extract something from it.

Update: to answer a comment in your question above...

var div = document.createElement('div');
div.appendChild(document.createTextNode('dsf'));
console.log( div.childNodes.length, div.childNodes, div.childNodes[0].textContent);​

I hope this makes a bit more sense to you know. The array appears empty in the console but it is not. check the length and attempt to access it and you will see.

Upvotes: 2

Paul
Paul

Reputation: 2520

.contents() is concerned with DOM nodes. That string in the 2nd example is not a DOM element.

Upvotes: -1

Related Questions