Skip to content

Commit df2937d

Browse files
committed
feat(jqLite): remove the attribute for .attr(attribute, null)
This change aligns jqLite with jQuery. Ref angular#15126 BREAKING CHANGE: Invoking `elem.attr(attributeName, null)` would set the `attributeName` atribute value to a string `"null"`, now it removes the attribute instead. To migrate the code follow the example below: Before: elem.attr(attributeName, null); After: elem.attr(attributeName, "null");
1 parent 6dc5e76 commit df2937d

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

src/jqLite.js

+7-5
Original file line numberDiff line numberDiff line change
@@ -654,11 +654,13 @@ forEach({
654654
return element.getAttribute(name) != null ? lowercasedName : undefined;
655655
}
656656
} else if (isDefined(value)) {
657-
element.setAttribute(name, value);
658-
} else if (element.getAttribute) {
659-
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
660-
// some elements (e.g. Document) don't have get attribute, so return undefined
661-
var ret = element.getAttribute(name, 2);
657+
if (value === null) {
658+
element.removeAttribute(name);
659+
} else {
660+
element.setAttribute(name, value);
661+
}
662+
} else {
663+
var ret = element.getAttribute(name);
662664
// normalize non-existing attributes to undefined (as jQuery)
663665
return ret === null ? undefined : ret;
664666
}

test/jqLiteSpec.js

+12
Original file line numberDiff line numberDiff line change
@@ -734,6 +734,18 @@ describe('jqLite', function() {
734734
expect(comment.attr('some-attribute','somevalue')).toEqual(comment);
735735
expect(comment.attr('some-attribute')).toBeUndefined();
736736
});
737+
738+
it('should remove the attribute for a null value', function() {
739+
var elm = jqLite('<div attribute="value">a</div>');
740+
elm.attr('attribute', null);
741+
expect(elm[0].hasAttribute('attribute')).toBe(false);
742+
});
743+
744+
it('should not remove the attribute for an empty string as a value', function() {
745+
var elm = jqLite('<div attribute="value">a</div>');
746+
elm.attr('attribute', '');
747+
expect(elm[0].getAttribute('attribute')).toBe('');
748+
});
737749
});
738750

739751

0 commit comments

Comments
 (0)