最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What's the point of the second argument in element.classList.toggle? - Stack Overflow

programmeradmin3浏览0评论

From MDN:

The toggle method has an optional second argument that will force the class name to be added or removed based on the truthiness of the second argument. For example, to remove a class (if it exists or not) you can call element.classList.toggle('classToBeRemoved', false); and to add a class (if it exists or not) you can call element.classList.toggle('classToBeAdded', true);

To my understanding, the classList is a token list, and lists, unlike arrays, can't have duplicate items. So adding an item to a list that already has it doesn't do anything and removing an item from a list that doesn't contain it (obviously) doesn't do anything, meaning that classList.toggle(className, true) is identical to classList.add(className) and classList.toggle(className, false) is identical to classList.remove(className).

Am I missing something?

P.S. no need to warn about IE compatibility issues.

From MDN:

The toggle method has an optional second argument that will force the class name to be added or removed based on the truthiness of the second argument. For example, to remove a class (if it exists or not) you can call element.classList.toggle('classToBeRemoved', false); and to add a class (if it exists or not) you can call element.classList.toggle('classToBeAdded', true);

To my understanding, the classList is a token list, and lists, unlike arrays, can't have duplicate items. So adding an item to a list that already has it doesn't do anything and removing an item from a list that doesn't contain it (obviously) doesn't do anything, meaning that classList.toggle(className, true) is identical to classList.add(className) and classList.toggle(className, false) is identical to classList.remove(className).

Am I missing something?

P.S. no need to warn about IE compatibility issues.

Share Improve this question asked May 14, 2014 at 19:11 willlmawilllma 7,5332 gold badges32 silver badges45 bronze badges 2
  • 2 I believe you are correct in that classList.toggle(className, false) is identical to classList.remove(className). However, using false is just a basic example. It is conceivable that there are scenarios where a conditional statement could be passed in as the second parameter. I can't think of an example off the top of my head, but this might be the purpose of it. – forgivenson Commented May 14, 2014 at 19:17
  • @Rudie Is there any difference between add and toggle(x, true)? Is there any difference between remove and toggle(x, false)? – willlma Commented May 14, 2014 at 19:23
Add a comment  | 

3 Answers 3

Reset to default 19

It would simply allow you to do something like this:

el.classList.toggle("abc", someBool);

instead of this:

if (someBool) {
    el.classList.add("abc");
} else {
    el.classList.remove("abc");
}

Unlike classList.add()/remove() classList.toggle() returns true when a class is added, and false when it’s removed — add() and remove() return undefined.

FYI IE11 doesn't support the optional 2nd add/remove param to classList.toggle().

classList.toggle like

el.classList.toggle("abc", someBool)  

is equivalent to :

let  hasClass  = el.classList.contains('abc')
  ;
if ( someBool && !hasClass ) el.classList.add('abc')
if (!someBool &&  hasClass ) el.classList.remove('abc')

To be more precise, with the return value:

function ToggleForce( element, nameOfClass, condition )
  {
  let hasClass = element.classList.contains( nameOfClass )
    ;
  if ( condition != hasClass )
    {
    if (hasClass) element.classList.remove( nameOfClass )
    else          element.classList.add( nameOfClass )
    // hasClass = !hasClass
    }
  return condition // hasClass
  }

The documentation on using this second argument force is a bit weak. Ultimately, the value of this condition determines whether the specified class(s) should be present(s) or not.
The subtlety of this argument is that it first checks whether it really needs to do an [add or remove] operation (a few microseconds saved?).
It's a bit counterintuitive, like many others I thought this boolean was being used to validate / invalidate the Toggle operation, and sure enough it seemed a little silly to me, the term Toggle might not be adequate, but now that I understand, I see no other possible.

Proof:
(with some elements for comparisons)

function ToggleForce( element, nameOfClass, condition )
  {
  let hasClass = element.classList.contains(nameOfClass)
    ;
  if ( condition != hasClass)
    {
    if (hasClass) element.classList.remove(nameOfClass)
    else          element.classList.add(nameOfClass)
    // hasClass = !hasClass
    }
  return condition
  }

btAdd.onclick =_=> { pElem.classList.add('toYellow');   console.clear() }
btRem.onclick =_=> { pElem.classList.remove('toYellow');console.clear() }
btTog.onclick =_=>
  {
  let res = pElem.classList.toggle('toYellow')
  console.clear()
  console.log(`toggle simple  : return = ${res}`)
  }
btTo5.onclick =_=>
  {
  let res = pElem.classList.toggle('toYellow', val.valueAsNumber<5)
  console.clear()
  console.log(`toggle force:(value < 5)=${val.valueAsNumber<5}, return=${res}`)
  }
btToT.onclick =_=>
  {
  let res = pElem.classList.toggle('toYellow', true)
  console.clear()
  console.log(`toggle force:true, return=${res}`)
  }
btToF.onclick =_=>
  {
  let res = pElem.classList.toggle('toYellow', false)
  console.clear()
  console.log(`toggle force:false, return=${res}`)
  }
btForce.onclick =_=> 
  {
    console.clear()

  let condition  = (val.valueAsNumber < 5)
    , hasClass   = pElem.classList.contains('toYellow')
    ,  msg       = 'no change'
    , classOnOff = ToggleForce( pElem, 'toYellow', (val.valueAsNumber<5) )
    ;
  //
  if ( condition && !hasClass ) msg = ' add class'
  if (!condition &&  hasClass ) msg = ' remove class'
  console.log(`return=${classOnOff}, condition=${condition}, hasClass=${hasClass}, --> ${msg}`)
  }
.toYellow{ background: yellow; }
<p id="pElem">test zone for class .toYellow { background: yellow; } </p>

value : <input id="val" type="number" value="6">
<br><br>

<button id="btAdd"> Add class </button>
<button id="btRem"> Remove class </button>
<br><br>
<button id="btTog"> tooggle simple</button>
<button id="btTo5"> toggle('toYellow', value < 5) </button>
<br><br>
<button id="btToT"> tooggle true </button>
<button id="btToF"> tooggle false </button>
<br><br>
<button id=btForce> <b>toggle('toYellow', value < 5)</b> <br> simulated by Add / remove method </button>

发布评论

评论列表(0)

  1. 暂无评论