I wanted to know if it\'s possible to add HTML tags to JavaScript alert()
method, such as:
-
et
alert()
doesn't support HTML, but you have some alternatives to format your message.
You can use Unicode characters as others stated, or you can make use of the ES6 Template literals. For example:
...
.catch(function (error) {
const alertMessage = `Error retrieving resource. Please make sure:
• the resource server is accessible
• you're logged in
Error: ${error}`;
window.alert(alertMessage);
}
Output:
As you can see, it maintains the line breaks and spaces that we included in the variable, with no extra characters.
You can use all Unicode characters and the escape characters \n
and \t
. An example:
document.getElementById("test").onclick = function() {
alert(
'This is an alert with basic formatting\n\n'
+ "\t• list item 1\n"
+ '\t• list item 2\n'
+ '\t• list item 3\n\n'
+ '▬▬▬▬▬▬▬▬▬ஜ۩۞۩ஜ▬▬▬▬▬▬▬▬▬\n\n'
+ 'Simple table\n\n'
+ 'Char\t| Result\n'
+ '\\n\t| line break\n'
+ '\\t\t| tab space'
);
}
<!DOCTYPE html>
<title>Alert formatting</title>
<meta charset=utf-8>
<button id=test>Click</button>
Result in Firefox:
You get the same look in almost all browsers.
You can add HTML into an alert string, but it will not render as HTML. It will just be displayed as a plain string. Simple answer: no.
This is not possible.
Instead, you should create a fake window in Javascript, using something like jQuery UI Dialog.
alert() is a method of the window object that cannot interpret HTML tags
No, you can use only some escape sequences - \n for example (maybe only this one).