ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 7일차 공부내용
    JavaScript 2021. 7. 24. 02:05

    1. The Document Object Model(DOM)

    DOM is a convention for describing the structure of an HTML document, and it’s at the heart of interacting with the browser. Conceptually, the DOM is a tree. A tree consists of nodes: every node has a parent (except for the root node), and zero or more child nodes. The root node is the document, and it consists of a single child, which is the <html> element. The <html> element, in turn, has two children: the <head> element and the <body> element

    Every node has the properties nodeType and nodeName.

    nodeType is an integer identifying what type of node it is. The Node object contains constants that
    map to these numbers. Browsers don’t do anything to enforce the uniqueness of IDs(though an HTML validator will catch these issues), so it is incumbent on you to ensure that IDs are unique.

     

    <!doctype html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>Simple HTML</title>
            <style>
                .callout {
                    border: solid 1px #ff0080;
                    margin: 2px 4px;
                    padding: 2px 6px;
                }
                .code {
                    background: #ccc;
                    margin: 1px 2px;
                    padding: 1px 4px;
                    font-family: monospace;
                }
            </style>
        </head>
        <body>
            <header>
                <h1>Simple HTML</h1>
            </header>
            <div id="content">
                <p>This is a <i>simple</i> HTML file.</p>
                <div class="callout">
                    <p>This is as fancy as we'll get!</p>
                </div>
                <p>IDs (such as <span class="code">#content</span>)
                are unique (there can only be one per page).</p>
                <p>Classes (such as <span class="code">.callout</span>)
                can be used on many elements.</p>
                <div id="callout2" class="callout fancy">
                    <p>A single HTML element can have multiple classes.</p>
                </div>
            </div>
        </body>
    </html>

     

    1.1 DOM “Get” Methods

    Every HTML element on a page may be assigned a unique ID, and document.getElementById can retrieve an element by its ID:

    document.getElementById('content'); // <div id="content">...</div>

    document.getElementsByClassName returns a collection of elements that have the given class name:

    const callouts = document.getElementsByClassName('callout');

    document.getElementsByTagName returns a collection of elements that have the given tag name:

    const paragraphs = document.getElementsByTagName('p');

     

    1.2 Querying DOM Elements

    The document methods querySelector and querySelectorAll allow you to use CSS selectors.

    CSS selectors allow you to identify elements by their name (<p>, <div>, etc.), their ID, their class (or combination of classes), or any combination thereof.

    . To identify elements by name, simply use the name of the element (without angle brackets). So a will match all <a> tags in the DOM, and br will match all the <br> tags. 

    . To identify elements by their class, use a period before the class name: .callout will match all elements that have the class callout. 

    . To match multiple classes, just separate them with periods: .callout.fancy will match all elements that have the class callout and the class fancy.

    . They can be combined:

    a#callout2.callout.fancy

    will match <a> elements with ID callout2, and classes callout and fancy.

    . If you separate multiple element selectors with a space, you can select nodes with a specific ancestry.

    For example, 

    #content p will select <p> elements that are descendants of whatever element has the ID content.

    #content div p will select <p> elements that are inside a <div> that are inside an element with the ID content

    . If you separate multiple elements selectors with a greater-than sign (>), you can select nodes that are direct children. 

    For example, 

    #content > p will select <p> elements that are children of an element with ID content

    . You can combine ancestry and direct child selectors

    For example,

    body .content > p will select <p> tags that are direct children of elements with class content that are descendants of <body>. 

     

    1.3 Manipulating DOM Elements

    Each element has two properties, text Content and innerHTML, that allow you to access (and change) the element’s content. textContent strips out all HTML tags and provides text data only, whereas innerHTML allows you to create HTML (which results in new DOM nodes). 

    const para1 = document.getElementsByTagName('p')[0];
    para1.textContent; // "This is a simple HTML file."
    para1.innerHTML; // "This is a <i>simple</i> HTML file."
    para1.textContent = "Modified HTML file"; // look for change in browser
    para1.innerHTML = "<i>Modified</i> HTML file"; // look for change in browser

     

    1.4 Creating New DOM Elements

    We can also explicitly create new nodes with document.createElement. This function creates a new element, but it doesn’t add it to the DOM; You’ll have to do that in a separate step.

    const p1 = document.createElement('p');
    const p2 = document.createElement('p');
    p1.textContent = "I was created dynamically!";
    p2.textContent = "I was also created dynamically!";

    To add these newly created elements to the DOM, we’ll use the insertBefore and appendChild methods.

    const parent = document.getElementById('content');
    const firstChild = parent.childNodes[0];
    
    parent.insertBefore(p1, firstChild);
    parent.appendChild(p2);

     

    1.5 Styling Elements

    if you want to change the style of an element, create a new CSS class, and then apply that class to the element(s)
    you wish to style. Using JavaScript, it is easy to apply an existing CSS class to an element.

    For example, if we wanted to highlight all paragraphs that contain the word unique, we would first create a new CSS class: 

    .highlight {
        background: #ff0;
        font-style: italic;
    }

    Every element has a property classList, which contains all of the classes (if any) the element has. classList has an add method that allows you to add further classes.

    function highlightParas(containing) {
        if(typeof containing === 'string')
            containing = new RegExp(`\\b${containing}\\b`, 'i');
        const paras = document.getElementsByTagName('p');
        console.log(paras);
        for(let p of paras) {
            if(!containing.test(p.textContent)) continue;
                p.classList.add('highlight');
        }
    }
    highlightParas('unique');
    function removeParaHighlights() {
        const paras = document.querySelectorAll('p.highlight');
        for(let p of paras) {
            p.classList.remove('highlight');
        }
    }

     

    1.6 Data Attributes

    HTML5 introduced data attributes, which allow you to add arbitrary data to HTML elements;

    this data isn’t rendered by the browser, but it does allow you to add information to elements that can easily be read and modified by JavaScript. 

    <button data-action="highlight" data-containing="unique">
        Highlight paragraphs containing "unique"
    </button>
    <button data-action="removeHighlights">
        Remove highlights
    </button>
    const highlightActions = document.querySelectorAll('[data-action="highlight"]');
    
    highlightActions[0].dataset;
    // DOMStringMap { containing: "unique", action: "highlight" }
    highlightActions[0].dataset.containing = "giraffe";
    highlightActions[0].dataset.caseSensitive = "true";

     

    1.7 Events

    The DOM API describes almost 200 events.

    const highlightActions = document.querySelectorAll('[data-action="highlight"]');
    for(let a of highlightActions) {
        a.addEventListener('click', evt => {
            evt.preventDefault();
            highlightParas(a.dataset.containing);
        });
    }
    
    const removeHighlightActions = document.querySelectorAll('[data-action="removeHighlights"]');
    for(let a of removeHighlightActions) {
        a.addEventListener('click', evt => {
            evt.preventDefault();
            removeParaHighlights();
        });
    }

    Every element has a method named addEventListener that allows you to specify a function that will be called when that event occurs. That function takes a single argument, an object of type Event.

    Many events have default handlers; If you want to prevent this behavior, call preventDefault() on the event object.

     

    'JavaScript' 카테고리의 다른 글

    fetch()  (0) 2021.08.14
    Promises  (0) 2021.08.14
    6일차 공부내용  (0) 2021.07.22
    5일차 공부내용 3  (0) 2021.07.21
    5일차 공부내용 2  (0) 2021.07.21
Designed by Tistory.