β Learn Javascript
Working with the dom
slides | md
5 min
Review the following sections and perform the activities on your own or with your group.
Perform the task(s) when you see this π emoji
Students who complete this module will be able to:
π View these properties and functions in the console (or access them with javascript using dot syntax).
window
{}
f
alert(123)
window.alert(123)
window.document
document
// get web page url property window.document.URL // get background color property window.document.bgColor // change the bgColor property window.document.bgColor = "red"
Many properties can be access with "vanilla" Javascript
// get the current URL window.alert(document.URL); // replace the content of the body window.document.body.innerHTML = "π" // return an array of all <a> elements on the page: window.document.querySelectorAll("a") // set a new location for this window: window.document.location = "https://davidson.edu"
<p id="greeting">Hello world</p>
// use #id to store reference to element let ele = document.querySelector("#greeting"); // get the text console.log(ele.textContent); // or set the text ele.textContent = "Hello world!";
submit
input
preventDefault
<form action="#"> <input type="text" id="color"> <input type="submit"> </form>
document.addEventListener("submit", function(e) { e.preventDefault(); let colorVal = document.getElementById("color").value; console.log(colorVal); document.body.bgColor = colorVal; })
jQuery is a Javascript library you will see often in code references. It provides easy access to properties and methods in the HTML DOM, but it is better to learn "pure JS".
NOTE: youmightnotneedjquery.com
// select all divs, set backgrounds red $('div').css({ 'background': 'red' }); // select all elements with myClass, add text to end $('.myClass').append(' - here is some new text');
Overview: Events and using forms with Javascript and jQuery
// click event with callback $('#submitButton').click(function() { // set the value of a form element $('#color').val("purple"); // do not perform the default form action return false; });
π Try it out
Presentation comments ...