Skip to content

Instantly share code, notes, and snippets.

@ericyork
Created November 16, 2023 15:55
Show Gist options
  • Save ericyork/456a1dd08f1ee28ec01e9562f34656e0 to your computer and use it in GitHub Desktop.
Save ericyork/456a1dd08f1ee28ec01e9562f34656e0 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript</title>
<!-- Internal (Inline) CSS -->
<style>
.red{
color: red;
}
</style>
</head>
<body>
<h1 id="id" class="class">Hello, World!</h1>
<button onclick="changeText()">Click me</button>
<!-- Internal (Inline) JS -->
<script>
// Declaring variables
var number = 10; // Number variable
var text = 'Hello, World!'; // String variable
var isTrue = true; // Boolean variable
// Changing the variables
var number = number + 5; // Adds 5 to the number variable
text = 'JavaScript is fun!'; // Changing variable values
console.log(isTrue); // Outputting values to the console
// Selecting elements
var elementById = document.getElementById('id'); // Selecting elements by ID
var elementsByClass = document.getElementsByClassName('class'); // Selecting elements by class name
// Changing an element's class
var element = document.getElementById('unique'); // Select the element by ID or class
element.classList.add('new-class'); // Add a class to the element
element.classList.remove('old-class'); // Remove a class from the element
element.classList.toggle('toggle-class'); // Toggle a class (adds the class if it's not present, removes if it's present)
// Functions
function changeText() { // This function (activated by the button with an onclick) adds and removes a class from the text element in the body
var text = document.getElementById('id'); // Select the element by ID or class
text.classList.toggle('red'); // Adds the class 'red' to the element if it's not present, and removes the class 'red' if it's already present
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment