3

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.

2
  • 1
    It appears as if the function will return an array of all objects with the custom attribute, toggle-state matching whatever state it has been toggled to. Interesting concept... Commented Oct 6, 2015 at 22:07
  • 1
    As a tip, I would add that when in doubt, open up the Chrome developer tools, find the code (on the source tab), put a break point on the JavaScript and when the break point is hit switch to the console tab and paste in the JavaScript. For example, if I put a break point on the return statement and when it was hit, I could paste $("[toggle-state='" + newState + "']") into the console tab and it would spit out an answer. Commented Oct 6, 2015 at 22:29

2 Answers 2

4

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.