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");
}
});
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.
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.
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With