代码之家  ›  专栏  ›  技术社区  ›  Radex

如何使用document.querySelector获取输入标记旁边的文本?

  •  -2
  • Radex  · 技术社区  · 7 年前

    我有下面的HTML,我需要在标记输入之后获取文本。 请注意文本 Some text 没有包装在任何标签中。

    你知道怎么得到它吗?

    <input type="checkbox" /> Some text
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Quentin    7 年前

    从本质上说,你不能。

    querySelector 只能返回一个元素(或 null ),文本不是元素。

    const input = document.querySelector("input");
    const text_node = input.nextSibling;
    console.log(text_node.data);
    <input type="checkbox" /> Some text

    可能 a label element .