Value of a variable becomes the id value

Asked

Viewed 179 times

0

business is as follows: I want to play a value of a js variable to become the id of a div in html.

<script>var x= 3;</script> 
<div id = "{x}"></div>

above is a visual example pq probably there is no way to give Property Binding with pure javascript. please help me!!

  • However, if you didn’t have Angularjs (v1) it wouldn’t work

3 answers

2


var x= 3;

//Loop em todos os elementos da página
for (const element of document.querySelectorAll('*')) {
    //Loop na lista de atributos do elemento
    for (const attribute of element.getAttributeNames()) {
        //Pega o atributo
        let attr = element.getAttribute(attribute);
        //Usa regex para pegar as variaveis
        const match = attr.match(/\{[^\{\}]+\}/g);
        //Se houver alguma
        if (match != null) {
            //Faz um loop, porque pode ser mais de uma
            for (let bindVariable of match) {
                //Retira o primeiro e último caracter, respectivamente, "{" e "}"
                bindVariable = bindVariable.substr(1, bindVariable.length-2);
                //Defini o novo atributo
                element.setAttribute(attribute, window[bindVariable]);
            }
        }
    }
}

//Mostra o elemento pelo novo id
console.log(document.getElementById(x));
<div id="{x}"></div>

This code has four problems (or more):

  1. Does many loops, including one of them is about ALL HTML elements on the page, which can considerably impair performance

  2. The variables used to do the Binding need to be declared before the code is executed, and the other codes that use that property with the new value need to be executed after

  3. This code assumes that all variables are in the object scope window, what may not be true

  4. This is just a simple version, changing the X value after loops does not update the values in the HTML elements

0

You can do it this way, but if you have more divs on the screen need to identify her somehow, because only informing the div he will add the id for all the divs of the document.

var x= 3;
$('div').prop('id', x);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>teste</div>

-2

Try using HTML DOM id Property

document.getElementById("myAnchor").id = "newid";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.