Skip to content

Commit

Permalink
Merge pull request #160 from lowlighter/feat-toggle-attribute
Browse files Browse the repository at this point in the history
feat: implement Element.toggleAttribute
  • Loading branch information
b-fuze authored May 5, 2024
2 parents 9121350 + 2f774ce commit ee4e7d2
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/dom/element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -801,6 +801,22 @@ export class Element extends Node {
}
}

toggleAttribute(rawName: string, force?: boolean) {
const name = String(rawName?.toLowerCase());
if (this.hasAttribute(name)) {
if ((force === undefined) || (force === false)) {
this.removeAttribute(name);
return false;
}
return true;
}
if ((force === undefined) || (force === true)) {
this.setAttribute(name, "");
return true;
}
return false;
}

hasAttribute(name: string): boolean {
return this.attributes[getNamedNodeMapValueSym](
String(name?.toLowerCase()),
Expand Down
44 changes: 44 additions & 0 deletions test/units/Element-toggleAttribute.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { DOMParser } from "../../deno-dom-wasm.ts";
import {
assert,
assertEquals,
} from "https://deno.land/[email protected]/testing/asserts.ts";

Deno.test("Element.toggleAttribute toggles attribute", () => {
const doc = new DOMParser().parseFromString(
`<input>`,
"text/html",
)!;

const input = doc.querySelector("input")!;
assert(!input.hasAttribute("disabled"));

for (const _ of [1, 2]) {
assertEquals(input.toggleAttribute("disabled", true), true);
assertEquals(input.outerHTML, `<input disabled="">`);
}

for (const _ of [1, 2]) {
assertEquals(input.toggleAttribute("disabled", false), false);
assertEquals(input.outerHTML, `<input>`);
}

for (const _ of [1, 2]) {
input.toggleAttribute("disabled", true);
assertEquals(input.outerHTML, `<input disabled="">`);
input.toggleAttribute("disabled", false);
assertEquals(input.outerHTML, `<input>`);
}
});

Deno.test("Element.toggleAttribute does not override value when forced", () => {
const doc = new DOMParser().parseFromString(
`<input disabled="disabled">`,
"text/html",
)!;

const input = doc.querySelector("input")!;
input.toggleAttribute("disabled", true);
assert(input.hasAttribute("disabled"));
assertEquals(input.outerHTML, `<input disabled="disabled">`);
});

0 comments on commit ee4e7d2

Please sign in to comment.