EasyBB
EasyBB

Reputation: 6574

Using JavaScript to get data-attr and replace that attr with a var

Ok so what I am trying to do is use javascript to get the attribute that I select, and use that as the javascript variable. Better if I show you anyways.

var a='<div id="element">Hello</div>';
var b="<span class="class">GoodBye</span>";
var c="<div id="element3">Filler Text</div>";
var d="<div id="element4">Filler text again</div>";
var e="<div id="element5">Filler text once more</div>";

$('.element').click(function(){
  var Element = $(this).attr('data-edit');
  $('#information_inner').html(Element);
  $('.pop_up').show();
 });

HTML markup would look like

<div class="element" data-edit="c"></div>

So we already know what is going to happen, the HTML will become c not the variable listed above. So how would you go about to retrieving the data-edit and changing it or making it to select as the javascript variable it list?

Upvotes: 1

Views: 110

Answers (1)

pauljz
pauljz

Reputation: 10901

You want to probably move those variables into an object:

var text = {
    a: '<div id="element">Hello</div>',
    b: '<span class="class">GoodBye</span>',
    c: '<div id="element3">Filler Text</div>',
    d: '<div id="element4">Filler text again</div>',
    e: '<div id="element5">Filler text once more</div>'
}

Then you can use, e.g., text['a'] to access one of these:

$('#information_inner').html( text[Element] );

Upvotes: 2

Related Questions