如果我有
<ul>
<li>...</li>
<li>...</li>
<li>Text before nested content
<ul>
<li>...</li>
<li>...</li>
</ul>
</li>
</ul>
如何通过JavaScript访问唯一Text before nested content
而不将其存储在元素中?
答案 0 :(得分:2)
这也是jQuery解决方案。
您可以设置class
元素的id
或li
(任何,以便您轻松选择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
此外,您还可以找到有关concat
,nodeType
和nodeName
属性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;
}
}