简体   繁体   English

在HTML中获取子元素的最佳做法是什么?

[英]What is the best practice to get a child of an element in HTML?

Something like get an variable out of class. 像从类中获取变量之类的东西。

ParentElement.someId.someId..

If i have something like that in css: 如果我在CSS中有类似的内容:

#someId #aaa #bbb
{
    ...
}

#someOtherId #aaa #bbb
{
    ...
}

and i want to get only the element under "#someId". 而且我只想获取“ #someId”下的元素。 Something like 就像是

getElementById("someId aaa bbb"); 

would be great, unfortunately this one doesn't work. 太好了,不幸的是,这不起作用。

Any ideas? 有任何想法吗?

If you have given an id to the element, you can say 如果您为元素指定了id ,则可以说

document.getElementById(childId)

Id must be unique in the document. ID在文件中必须是唯一的。

In your scenario, what I think you are having element with same Id at multiple places. 在您的方案中,我认为您在多个位置具有相同Id元素。 Either you can user class instead of id . 您可以使用用户class代替id

I assume you want to get the element in javascript, or what do you mean by "getting" in HTML? 我假设您要在javascript中获取元素,或者在HTML中“获取”是什么意思?

<div id="box">
    <div>Child element</div>
    <div>Child element</div>
</div>

You can access a specific element by getElementById('box'); 您可以通过getElementById('box');访问特定元素getElementById('box'); and you can access its children by getElementById('box').children . 您可以通过getElementById('box').children访问其getElementById('box').children So the first child would be getElementById('box').children[0] for example. 因此,第一个孩子将是例如getElementById('box').children[0]

Did that help you ? 这对您有帮助吗?

Id's are unique within the document so your ParentElement.someId.someId can simply be translated to document.getElementById(childId) . ID在文档中是唯一的,因此您的ParentElement.someId.someId可以简单地转换为document.getElementById(childId)

Regarding the sample CSS you posted, please note that you cannot have both situations in the same HTML at the same time, you can stylise differently based on the DOM hierarchy though. 关于您发布的示例CSS ,请注意,您不能同时在同一HTML中同时使用这两种情况,但是您可以根据DOM层次结构进行不同的样式设置。 With this in mind, you can use the same document.getElementById(childId) call. 考虑到这一点,您可以使用相同的document.getElementById(childId)调用。

ID should be unique, so you really shouldn't have elements with the same ID over and over, instead you can use class . ID应该是唯一的,因此您真的不应该一遍又一遍地使用具有相同ID的元素,而可以使用class

To access the element though, first you get the parent: 但是,要访问元素,首先要获得父元素:

var parent = document.getElementById("someId");

Then use querySelector on parent to get the desired element: 然后在父对象上使用querySelector获得所需的元素:

var element = parent.querySelector('.ELEMENT_CLASS');

And if it's id then: 如果是id,则:

var element = parent.querySelector('#ELEMENT_ID');

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

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