简体   繁体   English

如何访问没有 ID 的 HTML 元素?

[英]How to access HTML element without ID?

For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?例如在下面的代码片段中 - 我如何在知道父元素 ID(header-inner div)的情况下访问 h1 元素?

<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.查找具有给定 ID 的元素,查询具有给定标签名称的后代,返回第一个。 You could also loop on descendants to filter by other criteria;您还可以循环descendants以按其他条件进行过滤; 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).如果你开始朝那个方向发展,我建议你检查一个预先构建的库,比如 jQuery(会为你节省大量的时间来编写这些东西,它会有点棘手)。

If you were to use jQuery as mentioned by some posters, you can get access to the element very easily like so (though technically this would return a collection of matching elements if there were more than one H1 descendant):如果您要使用一些海报中提到的jQuery ,您可以像这样非常容易地访问该元素(尽管从技术上讲,如果有多个 H1 后代,这将返回一组匹配元素):

var element = $('#header-inner h1');

Using a library like JQuery makes things like this trivial compared to the normal ways as mentioned in other posts.与其他帖子中提到的常规方法相比,使用 JQuery 之类的库可以让这种事情变得微不足道。 Then once you have a reference to it in a jQuery object, you have even more functions available to easily manipulate its content and appearance.然后,一旦您在 jQuery 对象中引用了它,您就可以使用更多的函数来轻松地操作它的内容和外观。

If you are sure that there is only one H1 element in your div:如果您确定 div 中只有一个 H1 元素:

var parent = document.getElementById('header-inner');
var element = parent.GetElementsByTagName('h1')[0];

Going through descendants,as Shog9 showed, is a good way too.正如 Shog9 所展示的,通过后代也是一个好方法。

The simplest way of doing it with your current markup is:使用当前标记的最简单方法是:

document.getElementById('header-inner').getElementsByTagName('h1')[0].innerHTML = 'new text';

This assumes your H1 tag is always the first one within the 'header-inner' element.这假设您的 H1 标签始终是'header-inner'元素中的第一个标签。

To get the children nodes, use obj.childNodes , that returns a collection object.要获取子节点,请使用obj.childNodes ,它返回一个集合对象。

To get the first child, use list[0] , that returns a node.要获得第一个孩子,请使用list[0] ,它返回一个节点。

So the complete code should be:所以完整的代码应该是:

var div = document.getElementById('header-inner');
var divTitleWrapper = div.childNodes[0];
var h1 = divTitleWrapper.childNodes[0];

If you want to iterate over all the children, comparing if they are of class “title”, you can iterate using a for loop and the className attribute.如果要遍历所有子项,比较它们是否属于“title”类,可以使用 for 循环和className属性进行迭代。

The code should be:代码应该是:

var h1 = null;
var nodeList = divTitleWrapper.childNodes;
for (i =0;i < nodeList.length;i++){
    var node = nodeList[i];
    if(node.className == 'title' && node.tagName == 'H1'){
        h1 = node;
    }
}

Here I get the H1 elements value in a div where the H1 element which has CSS class="myheader":在这里,我在具有 CSS class="myheader" 的 H1 元素的 div 中获取 H1 元素值:

var nodes = document.getElementById("mydiv")
                    .getElementsByTagName("H1");

for(i=0;i<nodes.length;i++)
{
    if(nodes.item(i).getAttribute("class") == "myheader")
        alert(nodes.item(i).innerHTML);
}      

Here is the markup:这是标记:

<div id="mydiv">
   <h1 class="myheader">Hello</h1>
</div>

I would also recommend to use jQuery if you need a heavy parsing for your DOM.如果您需要对 DOM 进行大量解析,我还建议您使用jQuery

It's been a few years since this question was asked and answered.自从提出和回答这个问题以来已经有几年了。 In modern DOM, you could use querySelector :在现代 DOM 中,您可以使用querySelector

 document.querySelector('#header-inner h1').textContent = 'Different text';
 <div id='header-inner'> <div class='titlewrapper'> <h1 class='title'> Some text I want to change </h1> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM