10

次のいずれかのページがあります。

<span id='size'>33</span>

または

<span id='size'>
    <b>33</b>
    <strike>32</strike>
</span>

どちらの場合も値「33」を取得したいのですが、使用できるCSSセレクターはありますか?私は次の、b兄弟のない#sizeまたは#size兄弟であるbを使用しようとしました:

document.querySelector('#size:not(>b), #size>b').innerText

しかし、エラーが発生し続けます-「エラー:SYNTAX_ERR:DOM例外12」

w3仕様によると、シンプルセレクターのみがサポートされています。「大なり記号」(U + 003E、>)」は、シンプルセレクターの定義の一部と見なされます。

4

3 に答える 3

13

通常のCSSセレクターでは実行できませんが、JSの数行で実行できます。

var element = document.querySelector('#size');
var b = element.querySelector('b');
var text = b ? b.innerText : element.childNodes[0].nodeValue;

console.log(text);
于 2013-02-19T20:44:45.980 に答える
1

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;
    }
}
于 2013-02-19T20:48:41.087 に答える
0

CSSレベル4セレクターと親セレクターが用意される日には、単純なセレクターを使用できるようになりますが、今のところ、直接実行することはできません。

最初のテキストノードを見つけるために繰り返すことができますが、ここにハッキーな解決策があります:

var text = document.getElementById('size').innerHTML.split(/<.*?>/)[0];

要素の内容についてある程度の知識がある場合にのみ使用されます#size

于 2013-02-19T20:45:53.090 に答える