【问题标题】:Performing split on node returned by nextSibling returns TypeError undefined is not a function对 nextSibling 返回的节点执行拆分返回 TypeError undefined is not a function
【发布时间】:2014-10-19 16:47:54
【问题描述】:

我试图抓取一个元素旁边的一段文本,我可以使用它的类选择它,然后对其执行split(" "),但我得到了TypeError: undefined is not a function。我认为这是因为它不是字符串,所以当我尝试先将其转换为字符串时,它会返回 "[object Text]"

html:

<span class="status_abbr_inactive">
<figure class="planetIcon planet tooltip js_hideTipOnMobile" title="Planet"></figure>Hinata [1:28:10]</span>

当我表演时

document.getElementsByClassName("planetIcon planet tooltip js_hideTipOnMobile")[0].nextSibling

它返回"Hinata [1:28:10]",但对其执行 split() 不起作用。 我在这里错过了什么?

【问题讨论】:

    标签: javascript google-chrome-extension split nextsibling


    【解决方案1】:

    实际上,你用那行代码得到的是textNode

    要使用textNode 中包含的文本,您可以使用其.textContent 属性:

    var text = document.getElementsByClassName("planetIcon planet tooltip js_hideTipOnMobile")[0].nextSibling.textContent;
    
    var splitted = text.split(' ');
    // ["Hinata", "[1:28:10]"]
    

    【讨论】:

    • @RicoClark 请考虑将答案标记为正确,以便其他有相同问题的人可以轻松找到。
    • @RicoClark 哦,是的,我不记得那个限制了,抱歉。
    【解决方案2】:

    因为它是一个对象 - textNode。试试这个:

    alert(document.getElementsByClassName("planetIcon planet tooltip js_hideTipOnMobile")[0].nextSibling.nodeValue);
    

    【讨论】:

    • 而且 textNode 不是字符串。谢谢,效果很好。
    猜你喜欢
    • 1970-01-01
    • 2015-06-24
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 2015-01-14
    相关资源
    最近更新 更多