Skip to main content Accessibility Feedback

Manipulating elements after they’re rendered into the DOM

This week, I’m sharing topics from my next pocket guide: Vanilla JS Web Apps.

Yesterday we looked at how to render dynamic and conditional content into the DOM with vanilla JavaScript. Today, we’re going to learn how to further manipulate an element after it’s rendered.

Returning the element. #

The first and easiest way is to return our element after it’s rendered. Here’s our script so far.

var render = function (template, node) {
    if (!node) return;
    node.innerHTML = (typeof template === 'function' ? template() : template);
};

Let’s return the node element after it runs.

var render = function (template, node) {
    if (!node) return;
    node.innerHTML = (typeof template === 'function' ? template() : template);
    return node;
};

Now we can set our render() function to a variable and continue to work with it.

// Render the content
var mainContent = render('<h1>Hello world!</h1>', document.querySelector('#main'));

// Add a class
main.classList.add('margin-bottom-large');

Emit a custom event #

We may also want to expose our rendered element to other scripts. To do that, we’ll emit a custom event after it’s rendered using the CustomEvent API.

We should emit our event on the node, but set it to bubble so that you can listen for it further up the DOM.

var render = function (template, node) {
    if (!node) return;
    node.innerHTML = (typeof template === 'function' ? template() : template);
    var event = new CustomEvent('elementRenders', {
        bubbles: true
    });
    node.dispatchEvent(event);
    return node;
};

Now you can listen for rendered DOM elements like this.

document.addEventListener('elementRendered', function (event) {
    var elem = event.target; // The rendered element
}, false);

Here’s a working demo.

If you’ve already purchased the complete set of pocket guides, you’ll get “Vanilla JS Web Apps” as a free update when it comes out.

And if you haven’t, now’s the time to buy! The price will go up when the guide launches.


🚀 I just relaunched my Vanilla JS Pocket Guides with new code examples and real projects to help tie everything you’ll learn together. Check it out.

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips