Categories

.toggleAttr()

Categories: Attributes

.toggleAttr( attributeName, value, [ alternateValue ] )Returns: jQuery

Plugin: jQuery.fn.attr

Description: Add or remove a attribute from each element in the set of matched elements.

  • .toggleAttr( attributeName, value, [ alternateValue ] )

    version added: 1.0

    attributeName   The name of the attribute to toggle.

    value   A value to be toggled for each element in the matched set.

    alternateValue   A value to be set for each element in the matched set for preventing remove the attribute.

This method take attribute name and value as its parameter. If the value of the named attribute for the matched element the same as the givn value, the attribute will removed or replaced with the alternateValue.

  • Toggle attribute name for all input elements.

    HTML:
    <div>
      <input type="text" name="A" title="My title"/>
      <input type="text" name="C" title="My title"/>
      <input type="text" name="B"/>
    </div>
    Code:
    $('input').toggleAttr( 'title', 'My title' );
    Results:
    <div>
      <input type="text" name="A"/>
      <input type="text" name="B"/>
      <input type="text" name="C" title="My title"/>
    </div>
  • Toggle attribute name for all input elements, set old to prevent remove the attribute.

    HTML:
    <div>
      <input type="text" name="A" value="new"/>
      <input type="text" name="C" value="new"/>
      <input type="text" name="B" value="changed"/>
    </div>
    Code:
    $('input').toggleAttr( 'value', 'new', 'old' );
    Results:
    <div>
      <input type="text" name="A" value="old"/>
      <input type="text" name="C" value="old"/>
      <input type="text" name="B" value="new"/>
    </div>