JSFiddle - React, Tailwind, and code Playground

by psycketom

HTML

<img dx-bind-src="source" dx-bind-alt="description">

JavaScript

//-------------------------------------------------------
// The idea is to select, not elements, but attributes.
// Then, given the attributes, we can select the corresponding
// element and do manipulations.
// The attributes are *namespaced* with dx-bind for simplicity
// and easy of access, through XPath.
// Attribute values correspond to context key.
//-------------------------------------------------------
// The given example is a basic implementation of attribute binding.
//-------------------------------------------------------

// Selects all attribute nodes that start with "dx-bind".
var _elements = document.evaluate('descendant-or-self::*/attribute::*[starts-with(name(), "dx-bind")]', document, null, XPathResult.ANY_TYPE);

// Data collection.
var collection = {
    source : 'http://placehold.it/300x300',
    description : 'Courtesy of placehold.it'
};

//-------------------------------------------------------
// JavaScript tweak for working with plain XPathResult
//-------------------------------------------------------

// Resulting element cache.
var elements = [];

// Node cache.
var node;

// Transform XPathResult to Array.
while (node = _elements.iterateNext())
{
    elements.push(node);
}

//-------------------------------------------------------
// Actual implementation.
//-------------------------------------------------------

for (var i = 0; i < elements.length; i++)
{
    // Take attribute.
    var _element = elements[i];
    
    // Extract parent (actual element).
    var element = _element.ownerElement;
    
    // Extract actual attribute name.
    var attribute = _element.name.replace('dx-bind-', '');
    
    // Set attribute value to the data provided one.
    element.setAttribute(attribute, collection[_element.value]);
    
    // Cleanup.
    element.removeAttribute(_element.name);
}