jQuery: 2 DOM manipulation examples

This entry is part 13 of 33 in the series jQuery Tutorial

We use 2 simple examples to illustrate DOM manipulation concepts.

.after()
Insert content, specified by the parameter, after each element in the set of matched elements.
<!doctype html>
<html>
<head>
    <title>after demo</title>
    <style>
        p {
            background: yellow;
        }
    </style>
    <script src='//code.jquery.com/jquery-1.10.2.js'></script>
</head>
<body>

<p>I would like to say: </p>

<script>
    $('p').after('<b>Hello</b>');
</script>

</body>
</html>

Try The Code

From the example above, you could see that the Hello text is inserted after the <p> elements.

.append()
Insert content, specified by the parameter, to the end of each element in the set of matched elements.

Whereas, the text in the example below is inserted immediately after the elements using append.  This can also be called inline or in the same line insertion.

<!doctype html>
<html>
<head>
    <title>append demo</title>
    <style>
        p {
            background: yellow;
        }
    </style>
    <script src='//code.jquery.com/jquery-1.10.2.js'></script>
</head>
<body>

<p>I would like to say: </p>

<script>
    $('p').append('<strong>Hello</strong>');
</script>

</body>
</html>
Try The Code

jQuery: Dom Manipulation

This entry is part 12 of 33 in the series jQuery Tutorial

After selecting an element in the DOM, we can manipulate the DOM in a certain way.

There are 2 types of things that we will want to do after selecting the element.  We could modify the content inside the elements or we could retrieve the information from the elements.

A few of these methods—such as .attr().html(), and .val()—also act as “getters,” retrieving information from DOM elements for later use.

<!doctype html>
<html>
<head>
    <title>addClass demo</title>
    <script src='//code.jquery.com/jquery-1.10.2.js'></script>
    <style>
        p {
            margin: 8px;
            font-size: 16px;
        }
        .selected {
            color: blue;
        }
        .highlight {
            background: yellow;
        }
    </style>
</head>
<body>

<p>Hello</p>
<p>and</p>
<p>Goodbye</p>

<script>
    $('p').first().addClass('highlight');
    $('p').last().addClass('selected');
</script>

</body>
</html>

Try The Code

The <p> elements were first formed without any CSS formating.  We put the <script> near the end of the page just so that when the addclass is called, the <p> elements are ready in the document for changing.

Else, we can use the document ready method to ensure that the <p> elements have been formed before the <script> is ran.