With jQuery, how to find an data attribute on or within an element? (tree traversal)

Viewed 247

I have several unknown elements (Could be span, input, select, div, whatever):

<div id="SomeControl" >  <-- Data Attribute could be here
  <span>  <-- or Data Attribute could be here or even lower in the DOM
    ...  somewhere here is a data attribute: data-is-dirty="True"
   </span>
</div>

...

var $myControl = $('#SomeControl'); 

Using $myControl is there a way to find the existence and/or value of a given data attribute?

I've tried:

 var isDirty = $myControl.find(':has([data-is-dirty]').data('is-dirty');

Any suggestions would be appreciated.

4 Answers

Ways I could think about doing it without wrapping it in another element. Not a fan of any of them, maybe it will inspire others.

var horrible1 = $("#test").find("*").andSelf().filter("[data-is-dirty]").length;

var horrible2 = $("#test").find("[data-is-dirty]").andSelf().filter("[data-is-dirty]").length;


var elem = $("#test");
var horrible3 = elem.parent().find("#" + elem.attr("id") + "[data-is-dirty], #" + elem.attr("id") + " [data-is-dirty]").length;

var elem = $("#test");
var horrible4 = elem.find("[data-is-dirty]").add(elem.filter("[data-is-dirty]")).length;

var horrible5 = $("[data-is-dirty]").filter( "#test, #test *" ).length;

JSFiddle

var isDirty = $myControl.find('[data-is-dirty]');

Fiddle : http://jsfiddle.net/UpGQX/1/ Courtesy: gibberish

To select $myControl itself (if dirty):

var isDirty = $myControl.find('[data-is-dirty]');
var myControlIsDirty = $myControl.attr('data-is-dirty');
if (typeof myControlIsDirty !== 'undefined' && myControlIsDirty !== false) {
   isDirty.push($myControl);
}

or maybe even better:

var isDirty = $myControl.parent().find('[data-is-dirty]');
var isDirty=$("#SomeControl[data-is-dirty],#SomeControl [data-is-dirty]").data('is-dirty');

[Edit] Same idea, if you don't know the element id:

var isDirty=$someControl.data("is-dirty")||$("[data-is-dirty]",$someControl).data("is-dirty");
Related