javascript - 根据属性选择第一个 child

标签 javascript jquery

我希望能够选择一组特定的子项,其中定义了一个属性。

但是如何选择具有属性 data-role 的根选择器的第一个子节点的子节点?

first-of-type由于元素的类型,选择器不起作用。

这里有一个 DOM 示例。

<body>
    <div data-role="ca:panel" title="foo">
        <div data-role="ca:vbox" width="100%">
            <div data-role="ca:form">
                <div data-role="ca:formitem">
                    <div data-role="ca:hbox">
                        <input data-role="ca:textinput">
                        <div data-role="ca:menu"></div>
                    </div>
                </div>
                <div data-role="ca:formitem">
                    <input data-role="ca:passwordinput">
                </div>
                <div data-role="ca:formitem">
                    <select data-role="ca:combobox">
                        <option>[...]</option>
                    </select>
                </div>
            </div>
            <table>
                <tbody>
                    <tr>
                        <td>
                            <span data-role="ca:label"></span>
                        </td>
                        <td>
                            <button data-role="ca:button"></button>
                        </td>
                        <td>
                            <button data-role="ca:button"></button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

</body>

我的过滤器应该只选择

  • <div data-role="ca:form">
  • <span data-role="ca:label"></span>
  • <button data-role="ca:button"></button>
  • <button data-role="ca:button"></button>

它应该在任何情况下都有效,意思是,它不应该链接到 dom 的特定结构并且必须使用数据 Angular 色作为“选择器”。

我不是相关的 jQuery 开发人员。我尝试了一些选择器,例如 $('[data-role]:first-of-type');但它不起作用。

您有选择合适 child 的想法吗?

注意:找到第一个 parent 不是问题。

最佳答案

只要您有一个起始节点,就可以使用过滤器一般地执行此操作:

JS过滤器:http://jsfiddle.net/TrueBlueAussie/2uppww9s/5/

var root = $('[data-role="ca:vbox"]');
var matches = root.find('[data-role]').filter(function(){
    return $(this).parentsUntil(root, '[data-role]').length == 0;
});
alert(matches.length);

关于javascript - 根据属性选择第一个 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26161264/

相关文章:

javascript - 在自定义 'alert' 或 'confirm' 框中,剩余代码在按“确定”之前执行

javascript - typescript :如何定义具有许多未知键的对象

javascript - 如何在javascript中找到两个不不同数组的差异?我使用了下划线,但我对普通 JS 持开放态度

javascript - 正确终止 NodeJS Async Await

javascript - 切换 div 以放大并向左滑动

javascript - 在表格上添加复选框按钮

javascript - Bootstrap 数据表复选框更改类

javascript - 使用 listChanged 参数

javascript - 单击选项卡,选项卡消失

jquery构建http查询字符串