开发者

Check whether a div has a child with a certain attribute with jQuery

I'm trying to find the syntax to determine whether a div has a child div containing the data-role attribute set to header. I've tried these things with no luck:

$('div[data-role*="page"]').each(function(i) {
    if($(this).children('div').attr('data-role')=='header';) {
        alert("has header");
    }
});

$('div[data-role*="page"]').eac开发者_如何学Goh(function(i) {
    if($(this).children('div[data-role*="header"]').length!=0;) {
        alert("has header");
    }
});


In this example you have a trailing ; after !=0;

$('div[data-role*="page"]').each(function(i) {
    if ($(this).children('div[data-role="header"]').length != 0) {
        alert("has header");
    }
});

Example on jsfiddle.


Try:

if ($('div[data-role*="page"]').has("div[data-role=header]").size() > 0)
    alert("Has header");

Reference: http://api.jquery.com/has/


If I'm reading this correctly then the following should work:

$('div[data-role=page]:has(div[data-role])').css('border','1px solid #ccc');

to select any div that contains a child div with the attribute of 'data-role'.

JS Fiddle.

While you seem to want to utilise an if to trigger an alert(), this seems unnecessary since the above will function as a selector. If no elements are matched by that selector then, in the use-case I demonstrate, no elements will be affected. On the other hand, if an element is, or multiple elements are, selected then those will be.


This will select those divs that are child elements (with data-role attributes set to header) that are children of a div.

$('div > div[data-role=header]')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜