Javascript 如何获取以已知文本开头的“div”中的所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2617629/
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
How to get all elements inside "div" that starts with a known text
提问by Misha Moroshko
I have a divelement in an HTML document.
我div在 HTML 文档中有一个元素。
I would like to extract all elements inside this divwith idattributes starting with a known string (e.g. "q17_").
我想提取这里面所有的元素div与id属性的一个已知的字符串(如“q17_”)开始。
How can I achieve this using JavaScript?
如何使用 JavaScript实现这一点?
If needed, for simplicity, I can assume that all elements inside the divare of type inputor select.
如果需要,为简单起见,我可以假设里面的所有元素div都是input或类型select。
回答by karim79
var matches = [];
var searchEles = document.getElementById("myDiv").children;
for(var i = 0; i < searchEles.length; i++) {
if(searchEles[i].tagName == 'SELECT' || searchEles.tagName == 'INPUT') {
if(searchEles[i].id.indexOf('q1_') == 0) {
matches.push(searchEles[i]);
}
}
}
Once again, I strongly suggestjQuery for such tasks:
再次,我强烈建议使用jQuery 来完成这些任务:
$("#myDiv :input").hide(); // :input matches all input elements, including selects
回答by Casey Chu
Option 1:Likely fastest (but not supported by some browsersif used on Document or SVGElement) :
选项 1:可能最快(但如果在 Document 或 SVGElement 上使用,则某些浏览器不支持):
var elements = document.getElementById('parentContainer').children;
Option 2:Likely slowest :
选项 2:可能最慢:
var elements = document.getElementById('parentContainer').getElementsByTagName('*');
Option 3:Requires change to code (wrap a form instead of a div around it) :
选项 3:需要更改代码(用一个表单而不是一个 div 包裹它):
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;
var matches = [];
for (var i = 0; i < elements.length; i++)
if (elements[i].value.indexOf('q17_') == 0)
matches.push(elements[i]);
回答by Andrey Schoier
Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:
假设树中的每个新分支都是一个 div,我已经用 2 个函数实现了这个解决方案:
function fillArray(vector1,vector2){
for (var i = 0; i < vector1.length; i++){
if (vector1[i].id.indexOf('q17_') == 0)
vector2.push(vector1[i]);
if(vector1[i].tagName == 'DIV')
fillArray (document.getElementById(vector1[i].id).children,vector2);
}
}
function selectAllElementsInsideDiv(divId){
var matches = new Array();
var searchEles = document.getElementById(divId).children;
fillArray(searchEles,matches);
return matches;
}
Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:
现在假设您的 div 的 id 是“myDiv”,您所要做的就是创建一个数组元素并将其值设置为函数的返回值:
var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv = selectAllElementsInsideDiv('myDiv')
I have tested it and it worked for me. I hope it helps you.
我已经测试过了,它对我有用。我希望它能帮助你。
回答by William Beers
var $list = $('#divname input[id^="q17_"]'); // get all input controls with id q17_
// once you have $list you can do whatever you want
var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {
var id = $(this).prop("id"); // get id
var cbx = '';
if ($(this).is(':checkbox') || $(this).is(':radio')) {
// Need to see if this control is checked
}
else {
// Nope, not a checked control - so do something else
}
});
回答by aabhi
i have tested a sample and i would like to share this sample and i am sure it's quite help full. I have done all thing in body, first creating an structure there on click of button you will call a function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens. I have given alerts here on different level so u can test where r u now in the coding .
我已经测试了一个样本,我想分享这个样本,我相信它很有帮助。我已经在正文中完成了所有事情,首先在单击按钮时在那里创建一个结构,您将调用一个函数 selectallelement(); 单击鼠标,它将传递您想了解孩子的那个 div 的 id。我在这里给出了不同级别的警报,因此您可以测试现在在编码中的位置。
<body>
<h1>javascript to count the number of children of given child</h1>
<div id="count">
<span>a</span>
<span>s</span>
<span>d</span>
<span>ff</span>
<div>fsds</div>
<p>fffff</p>
</div>
<button type="button" onclick="selectallelement('count')">click</button>
<p>total element no.</p>
<p id="sho">here</p>
<script>
function selectallelement(divid)
{
alert(divid);
var ele = document.getElementById(divid).children;
var match = new Array();
var i = fillArray(ele,match);
alert(i);
document.getElementById('sho').innerHTML = i;
}
function fillArray(e1,a1)
{
alert("we are here");
for(var i =0;i<e1.length;i++)
{
if(e1[i].id.indexOf('count') == 0)
a1.push(e1[i]);
}
return i;
}
</script>
</body>
USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS
回答by Josh Gallagher
With modern browsers, this is easy without jQuery:
使用现代浏览器,这很容易,无需 jQuery:
document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');
The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^=which means "starts with".
querySelectorAll 接受一个选择器(根据 CSS 选择器)并使用它来递归搜索“yourParentDiv”元素的子元素。选择器使用^=这意味着“开始于”。
Note that all browsers released since June 2009 support this.
请注意,自 2009 年 6 月以来发布的所有浏览器都支持此功能。

