Giulia
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # DOM manipulation ## How can you use JavaScript to create an HTML element and then add it to your webpage? How would you replace an existing element with it? ## TWO STEP PROCESS <br> ### ONE - CREATE AND ADD ELEMENT (e.g. DIV or P) TO HTML #### CREATE createElement() #### INSERT appendChild() replaceChild() insertBefore() <br> ### TWO - INSERT CONTENT INSIDE NEW ELEMENT(e.g. text) #### CREATE CONTENT (E.G TEXT) e.g. creatTextNode() #### INSERT CONTENT (E.G TEXT) appendChild() replaceChild() insertBefore() <br> <br> <br> <br> HTML elements often consists of both an element node _and_ a text node.To create a header (e.g. h1), you must create both an h1 element and a text node. Start with div ``` <div> <h1> </h1> </div>` ``` Create new HTML element/node with document.createElement(); `var paragraph = document.createElement("p"); ` `<p></p>` We can add text if e.g. it's a new paragraph var text = document.createTextNode("New paragraph"); `<p>New paragraph</p>` Add text to paragraph with the appendChild method `paragraph.appendChild(text);` BUT this still wouldn't add the element on our document because we haven't specified WHERE the new element should be placed. That's why we need to add the paragraph inside the DIV: `document.querySelector("div").appendChild(paragraph); ` ``` <div> <h1> Title </h1> <p> New paragraph </p> </div> ``` ! The appendChild() method adds the node (=HTML element) to the end of the list of children of a specified parent node ## How would you add a `<li>` element to the start of a `<ul>`? Create new element ` var choc = document.createElement("li");` Create text node ` var textChoc = document.createTextNode("Hot chocolate");` Insert the text inside of the list item `choc.appendChild(textChoc);` Adding new li item to start of the list ` var list = document.querySelector("ul");` ` list.insertBefore(choc, list.childNodes\[0\]);` OR `list.insertBefore(choc, list.firstChild);` ## What is a JavaScript Event? What does event.preventDefault() do and why might you use it? Javascrip lets you execute code when an event is detected. An event can be (OnClick, mouseover ...) a user interacton. ```htmlmixed= <button>Click me</button> <p>No handler here.</p> <script> let button = document.querySelector("button"); button.addEventListener("click", () => { console.log("Button clicked."); }); </script> ``` Prevent default or false will stop the current behaviour. This is useful so you can add you own javascrpt for the event to behave in a different way. ```htmlmixed= <a href="www.google.com" onclick="return false">Click here</a> <a href="www.google.com" onclick="event.preventDefault()">here</a> ``` [Click here](#) [here](#) ## What is a NodeList? How is it different from an Array? The [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) object is a collection of nodes A `Node` is an interface that some DOM API object-types inherit; it allows these types to inherit the same set of methods A `NodeList` is returned from: `Node.childNodes`, `document.querySelectorAll()` - `Node.childNode()` (read-only) property returns a **live collection** where `Node` is a html element - changes in the DOM are reflected in the collection - In other case like `document.querySelectorAll()` the `NodeList` is a **static collection**. - Subsequent changes in the DOM does not affect the content of the collection. ```javascript= var parent = document.getElementById('parent'); var child_nodes = parent.childNodes; console.log(child_nodes.length); // let's assume "2" parent.appendChild(document.createElement('div')); console.log(child_nodes.length); // should output "3" ``` Here is a link to an [article](https://hackernoon.com/htmlcollection-nodelist-and-array-of-objects-da42737181f9) that further illustrates the comparison between Arrays, NodeList and HTMLCollections. > TL;DR: > - An HTMLCollection is a list of nodes. An individual node may be accessed by either index or the node’s name or id attributes. > Collections in the HTML DOM are assumed to be live meaning that they are automatically updated when the underlying document is changed. > - A NodeList object is a collection of nodes. The NodeList interface provides the abstraction of an ordered collection of nodes, without defining how this collection is implemented. > - NodeList objects in the DOM are live or static based on the interface used to retrieve them. > - `HTMLCollection` nor `NodeList` support the array prototype methods like `push` `pop` or `splice` methods. ```javascript= const childDivs = document.querySelectorAll('.divy') Array.isArray(childDivs) //=> false childDivs.constructor.name //=> NodeList const childDivsAgain = document.getElementsByClassName('divy') Array.isArray(childDivs) //=> false childDivs.constructor.name //=> HTMLCollection /*******************************************************/ // We can see that the HTMLCollection is literally live, // in the sense, any change to DOM is updated // automatically and available in the collection let parentDiv = document.getElementById('container') let nodeListDivs = document.querySelectorAll('.divy') // is a Static collection let htmlCollectionDivs = document.getElementsByClassName('divy') // is a Live collection nodeListDivs.length //=> 4 htmlCollectionDivs.length //=> 4 //append new child to container let newDiv = document.createElement('div'); newDiv.className = 'divy' parentDiv.appendChild(newDiv) nodeListDivs.length //=> 4 htmlCollectionDivs.length //=> 5 /*******************************************************/ // To convert the NodeList or HTMLCollection object to a // javascript array, you can do one of the following: const nodelist = document.querySelectorAll(‘.divy’) const divyArrayFrom = Array.from(nodelist) const divyArraySliced = Array.prototype.slice.call(nodelist) const divyArrayES6 = […document.querySelectorAll(‘.divy’)] ``` ### How is an `NodeList` different from `Arrays` | | `NodeList` | `Array` | | ------------- |:-------------:| :-----------: | | constains | `Node` | js primatives | | purpose | DOM specifc | js data structure | ### Properties `NodeList.length` -> The number of nodes in the `NodeList` ### Methods `NodeList.item()` -> Returns an item in the list by index, or null if the index is out-of-bounds Can be used as an alternative to simply accessing `nodeList[idx]`(which instead returns `undefined` when `idx` is out-of-bounds). `NodeList.entries()` -> Returns an `iterator` allowing to go through all key/value pairs contained in this object. `NodeList.forEach()` -> Executes a provided once per `NodeList` element. `NodeList.keys()` -> Returns an `iterator` allowing to go through all keys of the key/value paris contained in this object. `NodeList.values()` -> Returns an `iterator` allowing all values of the key/value pair contained in this object Using `for...in` or `for each...in` to enumerate the items in the list will also enumerate the length and item properties of the `NodeList`. `for...of` loops will loop over `NodeList` objects correctly ## What are the security concerns around `Element.innerHTML` and what could you use instead? - Setting `innerHTML` will destroy existing HTML elements that have event handlers attached to them, potentially creating a memory leak on some browsers. HTML ```htmlmixed= <p id="cool"> I like food <span>oranges</span> </p> ``` Javascript ```javascript= document.getElementById('cool').innerHTML = "This is the new paragraph." ``` Result ```htmlmixed= <p id="cool"> This is the new paragraph. </p> ``` ### Alternative ```javascript= var data = getData(); var p = document.getElementById("p1"); var text = document.createTextNode(data); p.replaceChild(text); // to append p.appendChild(text); // instead of p.innerHTML += text; ``` - `text` is a Text node. - `data` is a string containing the data to be put in the text node

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully