javascript 通过javascript访问div内的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7064554/
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
Access item inside div through javascript
提问by Muhammad Imran Tariq
I have a div which contain other tags inside it
我有一个包含其他标签的 div
<div id="mainDiv">
<div>
<table>
<tbody>
<tr>
<td>1</td>
<td>item</td>
<td>item</td>
<td>2</td>
</tr>
</tbody>
</table>
</div>
<div>
<table>
<tbody>
<tr>
<td>1</td>
<td>item</td>
<td>item</td>
<td>5</td>
</tr>
</tbody>
</table>
</div>
</div>
How can I access <td>
of this mainDiv through javascript. I want to change innerHTML of these <td>
如何<td>
通过 javascript访问这个 mainDiv。我想改变这些的innerHTML<td>
回答by Brian
var allDivTd = document.getElementById("mainDiv").getElementsByTagName("TD");
for(var i = 0; i < allDivTd.length; i++){
var td = allDivTd[i];
td.innerHTML = // do something w/ inner html
}
回答by StuperUser
Using jQuery: $('div#mainDiv td')
will return a set with all <td>
s in it.
使用 jQuery:$('div#mainDiv td')
将返回一个包含所有<td>
s的集合。
You can use .html()
to modify the content of them. See http://jsfiddle.net/StuperUser/vD3Tk/for an example.
您可以使用.html()
来修改它们的内容。有关示例,请参见http://jsfiddle.net/StuperUser/vD3Tk/。
Use jQuery if you're doing a lot of JS and have a lot of DOM manipulation to do. It has powerful and terse selector syntax from CSS, a lot of extension methods for DOM manipulation and cross browser compatibility. However, if you're only doing a small amount of JS, then don't feel it's necessary.
如果你正在做很多 JS 并且有很多 DOM 操作要做,请使用 jQuery。它具有来自 CSS 的强大而简洁的选择器语法,许多用于 DOM 操作和跨浏览器兼容性的扩展方法。但是,如果你只是做少量的JS,那么就觉得没有必要。
回答by emboss
You can use document.getElementsByTagNameto get all the tr
tags, and then iterate over them for accessing the individual td
s:
您可以使用document.getElementsByTagName获取所有tr
标签,然后遍历它们以访问单个td
s:
trs = document.getElementsByTagName('tr');
for (var i = 0; i < tr.length; i++) {
var tds = trs[i].childNodes;
for (var J = 0; j < tds.length; j++) {
var td = tds.childNodes[j];
// process td
}
}
}
Although , as you can see, this doesn't look to nice and is quite verbose. It's easier to use a Javascript framework such as jQuery, mootools, dojo... for these kinds of tasks. They support CSS selectors (e.g. jQuery) that let you traverse the DOM using CSS selectors, which are similar to XPath-style expressions and much more powerful than manual dom traversal with the few functions that Javascript originally provides for this.
虽然,如您所见,这看起来不太好,而且相当冗长。对于这些类型的任务,使用 Javascript 框架(例如 jQuery、mootools、dojo...)更容易。它们支持 CSS 选择器(例如jQuery),让您可以使用 CSS 选择器遍历 DOM,这些选择器类似于 XPath 样式的表达式,并且比手动 dom 遍历强大得多,并且具有 Javascript 最初为此提供的少数功能。
回答by Kevin Bowersox
var children = document.getElementById('mainDiv').getElementsByTagName('td');