Skip to content

Keep attribute order when removing an attribute - #645

Open
minilan677-netizen wants to merge 1 commit into
PuerkitoBio:masterfrom
minilan677-netizen:fix/remove-attr-keep-order
Open

minilan677-netizen wants to merge 1 commit into
PuerkitoBio:masterfrom
minilan677-netizen:fix/remove-attr-keep-order

Conversation

@minilan677-netizen

Copy link
Copy Markdown

Fixes #644

removeAttr deleted an attribute by moving the last attribute into its slot and shrinking the slice. That reordered the remaining attributes, so RemoveAttr, and RemoveClass/ToggleClass when the class attribute ends up empty, changed the rendered HTML beyond the removed attribute (<div id="i" href="/x" class="c" title="t" data-k="v"> with RemoveAttr("id") rendered as <div data-k="v" href="/x" class="c" title="t">).

It now uses slices.Delete, which keeps the other attributes in source order (as jQuery and the DOM do) and zeroes the freed slot as before.

Tests:

  • TestRemoveAttrKeepsAttributeOrder removes the first, a middle, the last and a missing attribute, and checks the rendered output.
  • TestRemoveClassKeepsAttributeOrder covers the RemoveClass path.

Both fail on master and pass with the change. The tests use div/p because x/net/html sorts the attributes of formatting elements such as <a> while parsing.

go test ./... -cover, go test -race ./..., go vet ./... (also with GOOS=windows) and gofmt pass with Go 1.27.3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RemoveAttr and RemoveClass change the order of the remaining attributes

1 participant