jQuery - DOM Manipulation

by Jennifer Piccione

HTML

<div id="container">
     <h1>Hello, DOM!</h1>

    <p>This is some fine fruit:</p>
    <ul class="listy">
        <li data-id="1">Apples</li>
        <li>Pears</li>
        <li>Cherries</li>
    </ul>
</div>

JavaScript

// I can minipulate content with
// .text()
// .html()
// .replaceWith()
// .remove()
// .detach()
// .clone()

console.clear();

// Getting the content of elements with .html();
var htmlValue = $(".listy").html();

// .text() will return as a string
var textValue = $(".listy").text();

console.log("Text value", textValue, "HTML Value", htmlValue);

// Set the inner content
//$(".listy li:first-child").html("Super Apples");

// Can set it with markup, too
//$(".listy li:first-child").html("<a href='#'>Link</a>");

// Swap out an element
//$(".listy li:first-child").replaceWith("<a href='#'>Link</a>");

// Entirely remove an element
//$(".listy li:first-child").remove();

// using a callback for more control
/*$(".listy li").html(function() {
   
    if (this.getAttribute('data-id')==1) {
        return "True";
    }
    
});/**/

// detach content to later insert
//var element = $(".listy").detach();

// now insert elsewhere
//element.insertAfter("h1");

// cloning/copying
//$(".listy li:last").clone().appendTo(".listy");