webworm
webworm

Reputation: 11019

jQuery selector on custom attribute value

I am trying to understand some jQuery syntax that I did not originally write.

<span id="mySpanElement" toggle-state="ON">Some Sample Text</span>

function switchOff(selectedControl) {
    var fieldName = selectedControl.attr('toggle-state');
    var newState = fieldName.replace("ON", "OFF");
    return $("[toggle-state='" + newState + "']");
}

In this function does the return statement pass back a reference to an element in the DOM that has an attribute of toggle-state=OFF? I have never seen a selector based upon a custom attribute before and was unsure if I am understanding it correctly.

Upvotes: 3

Views: 591

Answers (2)

Marcus Abrah&#227;o
Marcus Abrah&#227;o

Reputation: 696

It returns all elements with the attribute toggle-state equal to OFF.

Upvotes: 0

Travis J
Travis J

Reputation: 82267

The selector "[toggle-state='" + newState + "']" will match every element in the document that has the attribute toggle-state set to newState ("OFF" in this case).

Using that selector as an argument with jQuery will create a jQuery object that contains the resulting set of matches. That construction is what is being returned.

Here is a simple demonstration

function switchOff(){
 var newState = "OFF";
 return $("[toggle-state='" + newState  + "']")
}

$("#result").text(
    //$("[toggle-state='" + newState  + "']").length
    switchOff().length
);
[toggle-state="ON"]{
  color:green;
}
[toggle-state="OFF"]{
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div toggle-state="ON">Some Sample Text</div>
<div toggle-state="OFF">Some Sample Text</div>
<div toggle-state="OFF">Some Sample Text</div>
<div toggle-state="ON">Some Sample Text</div>
<div toggle-state="OFF">Some Sample Text</div>
<div id="result"><div>

Upvotes: 4

Related Questions