Browser API

Dialogues

Alert

alert ("This is a warning message!");

Confirmation

 
var retVal = confirm("Do you want to continue ?");
if (retVal == true) {
    console.log("User wants to continue!");
    return true;
} else {
    console.log("User does not want to continue!");
    return false;
}

DOM Manipulation

// Adding elements
 
// Appending strings
const body = document.body;
body.append("Hello World");
 
// Appending divs
const div = document.createElement('div')
body.append(div)
div.innerText = "Hello World"
 
// Render HTML inside a div
// Note: Security problem if users enter text
div.innerHTML = "<strong>Hi again</strong>"
 
// Easy secure option
const unsanitized_string = "abc <script>alert(1)<" + "/script> def";
document.getElementById("target").setHTML(unsanitized_string);
// Result (as a string): "abc  def"
 
// More secure version (from start)
const body = document.body
const div = document.createElement(div)
const strong = document.createElement(strong)
div.append(strong)
body.append(div)
 
// Modify attributes
const spanHi = document.querySelector("#hi")
spanHi.setAttribute("title", "hello there")
 
// Modifying classes
spanHi.classList.add("new-class")
spanHi.classList.toggle("hidden", true)
spanHi.style.backgroundColor = "red"