Select element without a child

后端 未结 3 1151
余生分开走
余生分开走 2020-12-20 15:02

I have a page that might one of the following:

33

Or


    <         


        
3条回答
  •  时光取名叫无心
    2020-12-20 15:45

    So really you want significant text (ie other than whitespace, because in your second example there's probably tabs and returns between the span start tag and the b) of #size, or, if that doesn't exist, the significant text of its first element:

    // Is text just whitespace?
    function isWhitespace(text){
        return text.replace(/\s+/,'').length === 0;
    }
    
    // Get the immediate text (ie not that of children) of element
    function getImmediateText(element){
        var text = '';
    
        // Text and elements are all DOM nodes. We can grab the lot of immediate descendants and cycle through them.
        for(var i = 0, l = element.childNodes.length, node; i < l, node = element.childNodes[i]; ++i){
        // nodeType 3 is text
            if(node.nodeType === 3){
                text += node.nodeValue;
            }
        }
    
        return text;
    }
    
    function getFirstTextNode(element){
        var text = getImmediateText(element);
    
        // If the text is empty, and there are children, try to get the first child's text (recursively)
        if(isWhitespace(text) && element.children.length){
            return getFirstTextNode(element.children[0])
        }
        // ...But if we've got no children at all, then we'll just return whatever we have.
        else {
            return text;
        }
    }
    

提交回复
热议问题