Backport of:

From 86747f1a1a7b4f0ea2d47fe94b841c224bae5073 Mon Sep 17 00:00:00 2001
From: "Miss Islington (bot)"
 <31488909+miss-islington@users.noreply.github.com>
Date: Sun, 21 Dec 2025 00:56:59 +0100
Subject: [PATCH] [3.13] gh-142754: Ensure that Element & Attr instances have
 the ownerDocument attribute (GH-142794) (#142819)

gh-142754: Ensure that Element & Attr instances have the ownerDocument attribute (GH-142794)
(cherry picked from commit 1cc7551b3f9f71efbc88d96dce90f82de98b2454)

Co-authored-by: Petr Viktorin <encukou@gmail.com>
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
---
 Lib/test/test_minidom.py                               | 10 +++++++++-
 Lib/xml/dom/minidom.py                                 |  2 ++
 .../2025-12-16-11-55-55.gh-issue-142754.xuCrt3.rst     |  4 ++++
 3 files changed, 15 insertions(+), 1 deletion(-)
 create mode 100644 Misc/NEWS.d/next/Library/2025-12-16-11-55-55.gh-issue-142754.xuCrt3.rst

--- python3.10-3.10.12.orig/Lib/test/test_minidom.py
+++ python3.10-3.10.12/Lib/test/test_minidom.py
@@ -10,7 +10,7 @@ import unittest
 import pyexpat
 import xml.dom.minidom
 
-from xml.dom.minidom import parse, Attr, Node, Document, parseString
+from xml.dom.minidom import parse, Attr, Node, Document, Element, parseString
 from xml.dom.minidom import getDOMImplementation
 from xml.parsers.expat import ExpatError
 
@@ -195,6 +195,14 @@ class MinidomTest(unittest.TestCase):
         # This example used to take at least 30 seconds.
         self.assertLess(end - start, 10)
 
+    def testSetAttributeNodeWithoutOwnerDocument(self):
+        # regression test for gh-142754
+        elem = Element("test")
+        attr = Attr("id")
+        attr.value = "test-id"
+        elem.setAttributeNode(attr)
+        self.assertEqual(elem.getAttribute("id"), "test-id")
+
     def testAppendChildFragment(self):
         dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
         dom.documentElement.appendChild(frag)
--- python3.10-3.10.12.orig/Lib/xml/dom/minidom.py
+++ python3.10-3.10.12/Lib/xml/dom/minidom.py
@@ -348,6 +348,7 @@ class Attr(Node):
     def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None,
                  prefix=None):
         self.ownerElement = None
+        self.ownerDocument = None
         self._name = qName
         self.namespaceURI = namespaceURI
         self._prefix = prefix
@@ -673,6 +674,7 @@ class Element(Node):
 
     def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None,
                  localName=None):
+        self.ownerDocument = None
         self.parentNode = None
         self.tagName = self.nodeName = tagName
         self.prefix = prefix
