Getting the contents of an element WITHOUT its children

前端 未结 5 1458
醉话见心
醉话见心 2020-12-10 11:18

I have a mild preference in solving this in pure JS, but if the jQuery version is simpler, then jQuery is fine too. Effectively the situation is like this

&l         


        
5条回答
  •  遥遥无期
    2020-12-10 12:11

    Pure JavaScript

    In this pure JavaScript example, I account for the possibility of multiple text nodes that could be interleaved with other kinds of nodes. Pass a containing NodeList in from calling / client code.

    function getText (nodeList, target)
    {
        var trueTarget = target - 1;
        var length = nodeList.length; // Because you may have many child nodes.
    
        for (var i = 0; i < length; i++) {
            if ((nodeList[i].nodeType === Node.TEXT_NODE) && (i === trueTarget)) {
                return nodeList.childNodes[i].nodeValue;
            }
        }
    
        return null;
    }
    

    You might use this function to create a wrapper function that uses this one to accumulate multiple text values.

提交回复
热议问题