如何访问没有ID的HTML元素? [英] How to access HTML element without ID?
本文介绍了如何访问没有ID的HTML元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如下面的代码段 - 如何访问知道父元素(header-inner div)的ID的h1元素?
For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?
<div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
谢谢!
推荐答案
function findFirstDescendant(parent, tagname)
{
parent = document.getElementById(parent);
var descendants = parent.getElementsByTagName(tagname);
if ( descendants.length )
return descendants[0];
return null;
}
var header = findFirstDescendant("header-inner", "h1");
找到具有给定ID的元素,查询具有给定标签名称的后代,返回第一个。您也可以循环后代
以过滤其他条件;如果你开始朝这个方向前进,我建议你检查一个预建的库,如jQuery(会节省你很多时间写这个东西,它有点棘手)。
Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on descendants
to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).
这篇关于如何访问没有ID的HTML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文