I want to write functions that create HTML elements and append child elements to each other, rather than echoing large chunks of HTML code or using echo <<<HEREDOC
.
createLoginBar
function will create a div that I will append to other HTML elements into my createLogoutBanner
function.
function createLoginBar() { $dom = new DOMDocument(); $login_bar = $dom->createElement('div'); $login_bar->setAttribute("id", "login_bar"); $dom->appendChild($login_bar); return $dom->saveHTML(); } function createLogoutBanner() { $dom = new DOMDocument(); $login_bar = createLoginBar(); $login_flex = createBlankLoginFlex(); $banner_login_form = createBannerLoginForm(); $login_message_flex = createLoginMessageFlex(); $nonmember_signup_flex = createNonSignupFlex(); $not_a_member_form = createNotAMemberForm(); $dom->appendChild($login_bar); //This line gives an error $login_bar->appendChild($login_flex); $login_flex->appendChild($banner_login_form); $login_bar->appendChild($login_message_flex); $login_bar->appendChild($nonmember_signup_flex); $nonmember_signup_flex->appendChild($not_a_member_form); return $dom->saveHTML(); }
createLogoutBanner
The line $dom->appendChild($login_bar);
in the function gives an error:
Fatal Error: Uncaught TypeError: DOMNode::appendChild(): Parameter #1 ($node) must be of type DOMNode, given in string.
Due to error condition
DOMNode::appendChild()
expected to be passed aDOMNode
.Your
createLoginBar
function returns a string instead of a node.Try the following changes:
Then you will see the error
Fatal Error: Uncaught DOMException: Bad Documentation Error
. This is because you must use the same parent instance of the DOMDocument to create the child nodes. Instead of creating a new DOMDocument in each function, create a top-level DOMDocument and pass it to each function to use.result:
sandbox