Elysia Tools

Browse tools, examples, visual explainers, and topic guides from one clear workspace.

Top Categories

Hubs

Language
ZHDERUPTENFRES

Elysia Tools

Navigation

Programming Languages

JavaScript examples: console, DOM and Fetch

Distinguish console snippets, browser DOM operations and network requests.

Samples

Entries inside this sample collection

CodejavascriptSimple

JavaScript Hello World

Basic JavaScript Hello World program and fundamental syntax examples

Difficulty

2/10

Estimated time

10 min

Tags

javascript, programming, beginner

Prerequisites

Basic programming concepts

javascript
// JavaScript Hello World Examples

// 1. Basic Hello World
console.log("Hello, World!");

// 2. Hello World with variable
const message = "Hello, World!";
console.log(message);

// 3. Hello World with function
function sayHello() {
    return "Hello, World!";
}
console.log(sayHello());

// 4. Hello World with template literals
const name = "World";
console.log(`Hello, ${name}!`);

// 5. Hello World in HTML
document.write('<h1>Hello, World!</h1>');

// 6. Hello World with alert (browser)
alert("Hello, World!");

// 7. Hello World with DOM manipulation
const heading = document.createElement('h1');
heading.textContent = 'Hello, World!';
document.body.appendChild(heading);

// 8. Hello World with ES6 arrow function
const greet = () => "Hello, World!";
console.log(greet());

// 9. Hello World with class
class Greeter {
    constructor(message = "Hello, World!") {
        this.message = message;
    }
    greet() {
        return this.message;
    }
}
const greeter = new Greeter();
console.log(greeter.greet());

// 10. Hello World with async/await
async function helloAsync() {
    return new Promise(resolve => {
        setTimeout(() => resolve("Hello, World!"), 1000);
    });
}
helloAsync().then(console.log);

// Basic data types examples
const number = 42;
const string = "Hello";
const isBoolean = true;
const array = [1, 2, 3];
const object = { name: "John", age: 30 };

console.log(typeof number);    // number
console.log(typeof string);    // string
console.log(typeof isBoolean); // boolean
console.log(typeof array);     // object
console.log(typeof object);    // object

// Control flow examples
if (number > 0) {
    console.log("Positive number");
} else {
    console.log("Non-positive number");
}

// Loop examples
for (let i = 0; i < 5; i++) {
    console.log(`Iteration ${i}`);
}

// Array methods examples
const fruits = ["apple", "banana", "cherry"];
fruits.forEach(fruit => console.log(fruit));

const upperFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(upperFruits); // ["APPLE", "BANANA", "CHERRY"]
CodejavascriptIntermediate

DOM Manipulation Examples

Interactive JavaScript examples showing DOM manipulation and event handling

Difficulty

5/10

Estimated time

15 min

Tags

javascript, dom, web, interactive

Prerequisites

Basic JavaScript, HTML basics

javascript
// JavaScript DOM Manipulation Examples

// 1. Selecting elements
const heading = document.getElementById('myHeading');
const paragraphs = document.querySelectorAll('p');
const container = document.querySelector('.container');

// 2. Creating elements
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello from JavaScript!';
newDiv.className = 'highlight';
newDiv.style.color = 'blue';

// 3. Appending elements
document.body.appendChild(newDiv);

// 4. Event handling
const button = document.createElement('button');
button.textContent = 'Click me!';
button.addEventListener('click', function() {
    alert('Button was clicked!');
});
document.body.appendChild(button);

// 5. Form handling
const input = document.createElement('input');
input.type = 'text';
input.placeholder = 'Enter your name';
input.addEventListener('input', function(e) {
    console.log('Input value:', e.target.value);
});

// 6. Dynamic content updates
const counter = document.createElement('div');
counter.textContent = 'Count: 0';
let count = 0;

const incrementBtn = document.createElement('button');
incrementBtn.textContent = 'Increment';
incrementBtn.addEventListener('click', function() {
    count++;
    counter.textContent = `Count: ${count}`;
});

document.body.appendChild(counter);
document.body.appendChild(incrementBtn);

// 7. CSS manipulation
const box = document.createElement('div');
box.style.width = '100px';
box.style.height = '100px';
box.style.backgroundColor = 'red';
box.style.margin = '10px';
box.addEventListener('mouseover', function() {
    this.style.backgroundColor = 'blue';
});
box.addEventListener('mouseout', function() {
    this.style.backgroundColor = 'red';
});
document.body.appendChild(box);

// 8. Working with attributes
const link = document.createElement('a');
link.href = 'https://example.com';
link.target = '_blank';
link.textContent = 'Visit Example';
link.setAttribute('title', 'Go to example.com');
document.body.appendChild(link);

// 9. List manipulation
const list = document.createElement('ul');
const items = ['Item 1', 'Item 2', 'Item 3'];

items.forEach(itemText => {
    const li = document.createElement('li');
    li.textContent = itemText;
    list.appendChild(li);
});

document.body.appendChild(list);

// 10. Event delegation
const container2 = document.createElement('div');
container2.innerHTML = `
    <button class="action-btn">Action 1</button>
    <button class="action-btn">Action 2</button>
    <button class="action-btn">Action 3</button>
`;

container2.addEventListener('click', function(e) {
    if (e.target.classList.contains('action-btn')) {
        console.log('Button clicked:', e.target.textContent);
    }
});

document.body.appendChild(container2);
CodejavascriptIntermediate

Fetch API Examples

Modern JavaScript fetch API examples for making HTTP requests

Difficulty

6/10

Estimated time

20 min

Tags

javascript, api, fetch, http

Prerequisites

Basic JavaScript, async/await, REST API concepts

javascript
// JavaScript Fetch API Examples

// 1. Basic GET request
fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => response.json())
    .then(data => console.log('Post:', data))
    .catch(error => console.error('Error:', error));

// 2. GET request with async/await
async function getPost(postId) {
    try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching post:', error);
    }
}

// 3. POST request
async function createPost(postData) {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(postData)
        });
        const data = await response.json();
        console.log('Created post:', data);
        return data;
    } catch (error) {
        console.error('Error creating post:', error);
    }
}

// Usage
createPost({
    title: 'My First Post',
    body: 'This is the body of my post',
    userId: 1
});

// 4. PUT request (update)
async function updatePost(postId, updateData) {
    try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(updateData)
        });
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error updating post:', error);
    }
}

// 5. DELETE request
async function deletePost(postId) {
    try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`, {
            method: 'DELETE'
        });
        if (response.ok) {
            console.log('Post deleted successfully');
        }
    } catch (error) {
        console.error('Error deleting post:', error);
    }
}

// 6. GET request with query parameters
async function getPostsByUser(userId) {
    try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching posts by user:', error);
    }
}

// 7. File upload simulation
async function uploadFile(file) {
    const formData = new FormData();
    formData.append('file', file);
    
    try {
        const response = await fetch('/upload', {
            method: 'POST',
            body: formData
        });
        const result = await response.json();
        return result;
    } catch (error) {
        console.error('Error uploading file:', error);
    }
}

// 8. Multiple concurrent requests
async function getUserAndPosts(userId) {
    try {
        const [userResponse, postsResponse] = await Promise.all([
            fetch(`https://jsonplaceholder.typicode.com/users/${userId}`),
            fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`)
        ]);
        
        const user = await userResponse.json();
        const posts = await postsResponse.json();
        
        return { user, posts };
    } catch (error) {
        console.error('Error fetching user and posts:', error);
    }
}

// 9. Request timeout with AbortController
async function fetchWithTimeout(url, timeout = 5000) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);
    
    try {
        const response = await fetch(url, {
            signal: controller.signal
        });
        clearTimeout(timeoutId);
        return await response.json();
    } catch (error) {
        if (error.name === 'AbortError') {
            console.error('Request timed out');
        } else {
            console.error('Error:', error);
        }
    }
}

// 10. Custom headers example
async function fetchWithHeaders() {
    try {
        const response = await fetch('https://api.example.com/data', {
            method: 'GET',
            headers: {
                'Authorization': 'Bearer your-token-here',
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        });
        return await response.json();
    } catch (error) {
        console.error('Error with custom headers:', error);
    }
}

Tools

Tools frequently paired with this sample

Related

Related sample collections

Related

Related workflows

Tool usage guide

Sample-focused context for search and workflow understanding

Overview

JavaScript snippets may need a browser page or a remote service. Choose a small fragment first, then check its environment and dependencies.

Choose a code card

Cards display and copy code. The first contains console.log, document and alert; the second manipulates DOM elements; the third shows GET and POST requests.

Do not assume an entire card runs unchanged everywhere. Select a fragment and provide its required page or service.

Choose a code card
Sample cardWhat to check
JavaScript Hello WorldBasic console output
DOM Manipulation ExamplesElements and events
Fetch API ExamplesRequests and response handling

Check dependencies

document and alert require a browser environment; DOM snippets add elements to the page. Fetch results depend on the network, server and cross-origin settings.

Run the chosen fragment in a test page or controlled environment, and inspect the console and DOM. Do not assume an example service gives a fixed response.

How it works

  1. 1Copy the desired snippet.
  2. 2Prepare a browser page or target runtime.
  3. 3Inspect the console, page or request result.

Edge cases & common failures

  • Runtime

    Fragments using document or alert need a browser-like environment.

  • Network

    Executing requests contacts an external service; inspect the address and data first.

Examples

1. Console baseline

How to use

Copy the first console.log from the first card into a browser console.

Outcome

The console shows Hello, World!; that single line does not depend on the DOM.

2. Create an element

How to use

Copy the newDiv creation, textContent assignment and body append from the second card into an empty test page.

Outcome

A div containing Hello from JavaScript! is added with class highlight and blue text.

3. Identify the method

How to use

Inspect the createPost function and fetch options in the third card.

Outcome

It uses POST and application/json; success depends on the endpoint and is not guaranteed by the example.

Hub

Infer JSON Schema from Samples and Spreadsheets

Derive a reviewable JSON Schema draft from representative JSON samples or XLSX rows, then inspect types, requiredness, nulls, and outliers before treating it as a contract.

Hub

Self-Hosted Giveaway Widget Review and Embed Handoff

Review giveaway configuration, merchant response samples, contrast and responsive layouts, then hand off identified widget files with browser acceptance evidence.

Home
Tools3212
Samples593
Visualizations471
Viewers103
Hubs239
Tags333
Images, Audio & Video657

Image, audio, and video processing, conversion, and optimization tools

Math, Date & Finance647

Calculators, numerics, date logic, statistics, and finance tools

Design & Color298

Color, layout, graphics, visual styling, and design helper tools

Text & Writing209

Writing, cleanup, formatting, extraction, and text analysis tools

Developer & Web193

Developer utilities, networking, web debugging, and automation helpers

Conversion & Encoding175

Format, file, archive, unit, and encoding conversion tools

Lead Generation Quiz Launch and Contact Handoff
Memorial Drafts: Family Review and Print Handoff
Private Habit Records: Backup, Restore and Sharing Review
Article to X and LinkedIn Drafts: Fact Review and Handoff
Markdown Interactive Deck Review and Offline Handoff

© 2026 Elysia Tools. All rights reserved.

DocsPricingAboutTerms of ServicePrivacy PolicyCookiesContact

Development

cURL to JavaScript (axios) Converter

Convert a cURL command into a JavaScript axios code snippet with config object, headers, and data

Development

cURL to JavaScript (fetch) Converter

Convert a cURL command into a JavaScript fetch() code snippet with headers, body, and method

Development

JavaScript Deobfuscator

Deobfuscate and analyze obfuscated JavaScript code to improve readability and understanding

Development

JavaScript Minifier

Compress JavaScript code

Development

JavaScript Obfuscator

Obfuscate JavaScript code using javascript-obfuscator for IP protection and reverse-engineering resistance

Programming Languages

Java Samples

Essential Java code examples and Hello World demonstrations

Programming Languages

C++ Samples

Essential C++ code examples and Hello World demonstrations

Programming Languages

Go Samples

Essential Go (Golang) code examples and Hello World demonstrations

Programming Languages

Python Samples

Essential Python code examples and Hello World demonstrations

Programming Languages

TypeScript Samples

Essential TypeScript code examples with type safety and Hello World demonstrations

Programming Languages

Zig Samples

Zig programming language examples - simple, efficient system programming with memory safety