Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
Custom Attributes values Javascript

The innline style Attributes has values such as style = "color: green; background: red;". If I want to dynamically change only the background I change with the javascript Attribute style, I do it with: element.style.background = "blue".

How to create a "custum Attributes" so that the values within an attribute change dynamically.

For example: myAttributes = "car: mercedes; truck: volvo;" so that I change only car values dynamically as style changes, as an element.myAttributes.car = "ferrari" or with setAttributes ("myAttributes", car = "ferrari" ). Is there a possibility to do this, or some similar alternative, some idea?

var get_att = document.getElementById("demo").getAttribute("vehicles");

// how to get vehicles attributes and convert to object?

const vehicles = {car:"mercedes", truck:"volvo"}; 
// const vehicles = get_att; 
// how to add the get_att variable here?

vehicles.car = "ferrari";

const setVehicles = (Object.entries(vehicles).map(([k, v]) => `${k}: ${v}`).join("; "));
console.log(setVehicles);

document.getElementById("demo").setAttribute("vehicles", setVehicles);
<div id="demo" vehicles="car: mercedes; truck: volvo"></div>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

HTML Attributes must be a string value you can't parse this like a object. For parse attributes you can you JSON.stringify() and JSON.parse() for setting you attribute values.

Example: setting:

const el = document.body 
el.setAttribute("my-attribute", JSON.stringify({car: "bmw", owner: "user1234"}))

and parse

    JSON.parse(document.body.getAttribute('my-attribute'))
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use dataset for that purpose. Here is a small demo:

let div = document.querySelector("div");

Object.assign(div.dataset, { water: "Morshinska", juice: "Sandora" });

console.log(div.dataset.water);

div.dataset.water = "Spa";

console.log(div.dataset.water);

console.log(Object.entries(div.dataset)
                  .map(([k, v]) => `${k}: ${v}`)
                  .join("; "));
<div></div>

Solution more close to your format

Although this is not best practice (due to the limitations on the allowed characters in this format), here are some helper functions to get and set individual properties in the attribute syntax you want to use:

function getMyAttributes(elem) {
    const regex = /([^:;=]*):([^:;=]*)/g
    return Object.fromEntries(Array.from(elem.dataset.myattr?.matchAll(regex)??[], ([_, k, v]) =>
        [k.trim(), v.trim()]
    ));
}

function setMyAttributes(elem, obj) {
    const regex = /[:;]/g;
    elem.dataset.myattr = Object.entries(obj).map(([k, v]) => {
        if (regex.test(k) || regex.test(v)) throw "Invalid character in key/value pair";
        return `${k}: ${v};`;
    }).join(" ");
}

function setMyAttribute(elem, key, value) {
    setMyAttributes(elem, {...getMyAttributes(elem), ...{[key]: value}});
}

function getMyAttribute(elem, key) {
    return getMyAttributes(elem)[key];
}

// Demo
let div = document.querySelector("div");
console.log(getMyAttribute(div, "water"));
setMyAttribute(div, "water", "Spa");
console.log(getMyAttribute(div, "water"));
console.log(div.dataset.myattr);
<div data-myattr="water: Morshinska; juice: Sandora;"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda