如何访问没有 ID 的 HTML 元素? [英] How to access HTML element without ID?
本文介绍了如何访问没有 ID 的 HTML 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如在下面的代码段中 - 我如何在知道父元素的 ID(header-inner div)的情况下访问 h1 元素?
<div class='titlewrapper'><h1 class='title'>我想更改的一些文字
谢谢!
解决方案
function findFirstDescendant(parent, tagname){parent = document.getElementById(parent);var后代 = parent.getElementsByTagName(tagname);如果(后代.长度)返回后代[0];返回空;}var header = findFirstDescendant("header-inner", "h1");
查找具有给定 ID 的元素,查询具有给定标签名称的后代,返回第一个.您还可以循环 descendants
以按其他条件过滤;如果您开始朝这个方向发展,我建议您查看一个预构建的库,例如 jQuery(这会为您节省大量编写这些内容的时间,它会变得有些棘手).
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>
Thanks!
解决方案
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");
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屋!
查看全文