Skip to content
Advertisement

create variables from each element’s id attribute

need to create a variable from each element’s id attribute – using jquery
as a final result – btngo.on('click'... – should work
any help

$('body *').each(function(){
    if($(this).attr('id')){
        var id = $(this).attr('id');
    console.log(id); // ok
        $(window)[id] = $(this); // here is the problem
    }
});

btngo.on('click', function(){
    console.log('btngo clicked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='btngo'>GO</button>

Advertisement

Answer

simply

document.body.querySelectorAll('[id]').forEach(el=>console.log(el.id))
btngo.onclick = () => console.log('btngo clicked' )

/* same as:

window.btngo.onclick = () => console.log('btngo clicked' )

// or 

window['btngo'].onclick = () => console.log('btngo clicked' )

--------*/
<button id='btngo'>GO</button>

within an array :

const Elements = [...document.body.querySelectorAll('[id]')]
    .reduce((list, el) => 
      {
      list[el.id] = document.getElementById(el.id)
      return list
      }, {})
 
Elements['btngo'].onclick = () => console.log('btngo clicked' )
<button id="btngo">Click me</button>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement