Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]').each(function(i) {
    if($(this).children('div[data-role*="header"]').length!=0;) {
        alert("has header");
    }
});
like image 756
vee Avatar asked Feb 21 '11 15:02

vee


People also ask

How do you check if an element has an attribute in jQuery?

Using jQuery The idea is to use the . attr() method, which returns the attribute's value for an element if it is present and returns undefined if the attribute doesn't exist.

How do you get children of children in jQuery?

The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

How do you get the children of the $( this selector?

Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.


2 Answers

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.

like image 98
Mark Coleman Avatar answered Sep 30 '22 08:09

Mark Coleman


Try:

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

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

like image 23
Chris Laplante Avatar answered Sep 30 '22 06:09

Chris Laplante