How do I use document.createElement()
to create an dismissable alert?
I am trying to add the below alert:
<div role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
Using the document.createElement()
function as seen in the code below:
document.createElement('
<div role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>'
);
But keep getting the below error message: Uncaught SyntaxError: Invalid or unexpected token
.
The browser console suggest that the error is in this line <div role="alert">
What am I doing wrong?
CodePudding user response:
you cannot use createElement like that.
Syntax
createElement(tagName)
createElement(tagName, options)
tagName
A string that specifies the type of element to be created. The nodeName of the created element is initialized with the value of tagName. Don't use qualified names (like "html:a") with this method. When called on an HTML document, createElement() converts tagName to lower case before creating the element. In Firefox, Opera, and Chrome, createElement(null) works like createElement("null").
please refer mdn documantation.
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
in this case, you can use DOMParser to parse the string to HTMLElement.
e.g.
const parser = new DOMParser()
const dom = parser.parseFromString(`
<div role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>`, 'text/html')
console.log(dom.body.firstChild)