javascript访问嵌套标记之前的文本

时间:2013-09-24 23:20:15

标签: javascript html5 nested-lists

如果我有

<ul>
  <li>...</li>
  <li>...</li>
  <li>Text before nested content
    <ul>
      <li>...</li>
      <li>...</li>
    </ul>
  </li>
</ul>

如何通过JavaScript访问唯一Text before nested content而不将其存储在元素中?

2 个答案:

答案 0 :(得分:2)

这也是jQuery解决方案。

您可以设置class元素的idli任何,以便您轻松选择element)并使用以下内容用于获取所需数据的代码:

$("<SELECTOR FOR LI>")
    .clone()    // clone the element
    .children() // select all the children
    .remove()   // remove all the children
    .end()      // again go back to selected element
    .text();    // get the text of element

有关详细信息,请阅读this article
您还可以在JSFiddle中查看此工作示例。

<强>更新

您也可以使用pure JavaScript执行此操作。

只需iterate个子节点(如果至少有一个),检查节点类型(3,表示它是text node),如果是true,{{ 1}}这是其余部分的文字。

以下是JSFiddle中的工作示例 有关节点类型的更多信息,请查看this link 此外,您还可以找到有关concatnodeTypenodeName属性here的有用信息。

答案 1 :(得分:1)

jsFiddle Demo

您应该迭代直到找到嵌套内容,然后返回包含文本的第一个childNode。

var top = document.getElementsByTagName("ul")[0];
for( var child in top ){
 var c = top[child];
 if( !c.hasOwnProperty("nodeName") )continue;
 if( c.children.length > 0 ){
  alert(c.childNodes[0].textContent);
  break;
 }
}