Using data attribute to pull in JS content

So I’m not too familiar with data attributes and I wanted to see if I get can get some help from others.

I have an HTML portion as shown below:

<div class="columns is-multiline app-list"></div>

The app-list is being rendered by the following JS:

function apps_menu() {
    const apps_target = document.querySelector('.app-list');

    wp.api.loadPromise.done(function () {
        const menus = wp.api.collections.Posts.extend({
            url: wpApiSettings.root + 'menus/v1/locations/application_launcher',
        });
        const Menus = new menus();
        Menus.fetch()
            .then(posts => {
                let post_list = posts.items;
                post_list.forEach(function (post) {
                    apps_target.appendChild(create_apps_dom_tree(post));
                });
            });
    });

    function create_apps_dom_tree(post) {
        const {
            url,
            post_title,
            post_image = document.location.origin + '/images/o365/'
        } = post
        const container = document.createElement('div');
        container.className = 'column is-one-third is-flex py-0';
        const anchor = document.createElement('a');
        anchor.href = url;
        anchor.className = 'dropdown-item px-2 is-flex is-align-items-center';
        const figure = document.createElement('figure');
        figure.className = 'image is-32x32 is-flex';
        const img = document.createElement('img');
        img.src = `${post_image}${post_title}.svg`;
        const span = document.createElement('span');
        span.className = 'pl-2';
        span.textContent = post_title;
        figure.appendChild(img);
        anchor.append(figure, span);
        container.appendChild(anchor);
        return container;
    }
}

Is there a way that instead of calling app-list as a class, that I can do something like this:

<div class="columns is-multiline" data-source="application_launcher"></div>?

All help would be appreciated!

161 thoughts on “Using data attribute to pull in JS content”

Leave a Comment