按类和 ID 获取元素内的元素 - JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7815374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get element inside element by class and ID - JavaScript
提问by Tanner Babcock
Alright, I've dabbled in JavaScript before, but the most useful thing I've written is a CSS style-switcher. So I'm somewhat new to this. Let's say I have HTML code like this:
好吧,我以前接触过 JavaScript,但我写的最有用的东西是 CSS 样式切换器。所以我对此有点陌生。假设我有这样的 HTML 代码:
<div id="foo">
<div class="bar">
Hello world!
</div>
</div>
How would I change "Hello world!" to "Goodbye world!" ? I know how document.getElementByClass and document.getElementById work, but I would like to get more specific. Sorry if this has been asked before.
我将如何更改“Hello world!” 到“再见世界!” ? 我知道 document.getElementByClass 和 document.getElementById 是如何工作的,但我想更具体一些。抱歉,如果之前已经问过这个问题。
回答by Joseph Marikle
Well, first you need to select the elements with a function like getElementById
.
好吧,首先您需要选择具有类似函数的元素getElementById
。
var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];
getElementById
only returns one node, but getElementsByClassName
returns a node list. Since there is only one element with that class name (as far as I can tell), you can just get the first one (that's what the [0]
is for—it's just like an array).
getElementById
只返回一个节点,但getElementsByClassName
返回一个节点列表。由于只有一个具有该类名的元素(据我所知),您可以获取第一个元素(这[0]
就是它的用途——它就像一个数组)。
Then, you can change the html with .textContent
.
然后,您可以使用 .html 更改 html .textContent
。
targetDiv.textContent = "Goodbye world!";
var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];
targetDiv.textContent = "Goodbye world!";
<div id="foo">
<div class="bar">
Hello world!
</div>
</div>
回答by jfriend00
You can do it like this:
你可以这样做:
var list = document.getElementById("foo").getElementsByClassName("bar");
if (list && list.length > 0) {
list[0].innerHTML = "Goodbye world!";
}
or, if you want to do it with with less error checking and more brevity, it can be done in one line like this:
或者,如果你想用更少的错误检查和更简洁的方式来完成,可以像这样在一行中完成:
document.getElementById("foo").getElementsByClassName("bar")[0].innerHTML = "Goodbye world!";
In explanation:
在解释:
- You get the element with
id="foo"
. - You then find the objects that are contained within that object that have
class="bar"
. - That returns an array-like nodeList, so you reference the first item in that nodeList
- You can then set the
innerHTML
of that item to change its contents.
- 你用
id="foo"
. - 然后,您会找到包含在该对象中的具有
class="bar"
. - 这将返回一个类似数组的 nodeList,因此您引用该 nodeList 中的第一项
- 然后,您可以设置该
innerHTML
项目的 以更改其内容。
Caveats: some older browsers don't support getElementsByClassName
(e.g. older versions of IE). That function can be shimmed into place if missing.
注意事项:一些较旧的浏览器不支持getElementsByClassName
(例如较旧版本的 IE)。如果缺少该功能,可以将其填充到位。
This is where I recommend using a library that has built-in CSS3 selector support rather than worrying about browser compatibility yourself (let someone else do all the work). If you want just a library to do that, then Sizzle will work great. In Sizzle, this would be be done like this:
这是我建议使用具有内置 CSS3 选择器支持的库的地方,而不是自己担心浏览器兼容性(让其他人完成所有工作)。如果你只想要一个图书馆来做到这一点,那么 Sizzle 会很好用。在 Sizzle 中,这将是这样完成的:
Sizzle("#foo .bar")[0].innerHTML = "Goodbye world!";
jQuery has the Sizzle library built-in and in jQuery, this would be:
jQuery 内置了 Sizzle 库,在 jQuery 中,这将是:
$("#foo .bar").html("Goodbye world!");
回答by John Hartsock
If this needs to work in IE 7 or lower you need to remember that getElementsByClassName does not exist in all browsers. Because of this you can create your own getElementsByClassName or you can try this.
如果这需要在 IE 7 或更低版本中工作,您需要记住 getElementsByClassName 并不存在于所有浏览器中。因此,您可以创建自己的 getElementsByClassName 或尝试此操作。
var fooDiv = document.getElementById("foo");
for (var i = 0, childNode; i <= fooDiv.childNodes.length; i ++) {
childNode = fooDiv.childNodes[i];
if (/bar/.test(childNode.className)) {
childNode.innerHTML = "Goodbye world!";
}
}
回答by Avi Shimshilashvili
Recursive function :
递归函数:
function getElementInsideElement(baseElement, wantedElementID) {
var elementToReturn;
for (var i = 0; i < baseElement.childNodes.length; i++) {
elementToReturn = baseElement.childNodes[i];
if (elementToReturn.id == wantedElementID) {
return elementToReturn;
} else {
return getElementInsideElement(elementToReturn, wantedElementID);
}
}
}
回答by Benjamin Werner
THe easiest way to do so is:
最简单的方法是:
function findChild(idOfElement, idOfChild){
let element = document.getElementById(idOfElement);
return element.querySelector('[id=' + idOfChild + ']');
}
or better readable:
或更好的可读性:
findChild = (idOfElement, idOfChild) => {
let element = document.getElementById(idOfElement);
return element.querySelector(`[id=${idOfChild}]`);
}
回答by hardik akbari
You should not used document.getElementByIDbecause its work only for client side controls which ids are fixed . You should use jquery instead like below example.
您不应该使用document.getElementByID,因为它仅适用于客户端控制哪些 id 是固定的。您应该像下面的示例一样使用 jquery。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="foo">
<div class="bar">
Hello world!
</div>
</div>
use this :
用这个 :
$("[id^='foo']").find("[class^='bar']")
// do not forget to add script tags as above
if you want any remove edit any operation then just add "." behind and do the operations
如果你想要任何删除编辑任何操作,那么只需添加“。” 后面做操作