0

I have the following code, where I'm attempting to get a series of element_1, element_2 and so on, and then choose one of them at random.

With this code, where I have console.log(element_count); that will log 1, 2 and so on as expected.

However, all of this results in random_element literally becoming "element_2" instead of $('<div class="fruit oranges">2</div>').

Is it something with element_counted = 'element_' + element_count;?

jQuery(document).ready(function($) {
  var element_count = 0;

  var element_1 = $('<div class="fruit apples">1</div>');

  var element_count = element_count + 1,
    element_counted = 'element_' + element_count;
  console.log(element_count);

  var element_2 = $('<div class="fruit oranges">2</div>');

  var element_count = element_count + 1,
    element_counted = 'element_' + element_count;
  console.log(element_count);

  var random_element = element_counted; // This becomes 'element_2' instead of element_2's variable content.
  console.log(random_element);
  $('.element-placeholder').replaceWith(random_element);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class=".element-placeholder">element_2</div>
<!--This should be one of the .fruit divs instead of the text "pane_2"-->
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Nathan
  • 377
  • 1
  • 6
  • 16
  • Remove the dot from class=".element-placeholder" – mplungjan Jan 27 '21 at 15:41
  • 1
    Also you have `element_counted = 'element_' + element_count;` so it will generate `element_2` as you request – mplungjan Jan 27 '21 at 15:42
  • A variable does not gain the value of another variable just because it holds a string with the same name as another variable. – Heretic Monkey Jan 27 '21 at 15:43
  • @HereticMonkey - that's what I figure is incorrect. So how to get `element_counted` to equal `element_1 ` which equals `$('
    1
    ');` - instead of literally equalling the text "element_1"
    – Nathan Jan 27 '21 at 20:51

1 Answers1

0

You try to access an element by accessing a string that holds the name

I think you meant to do this

$(function() {
  const elements = [
    $('<div class="fruit apples">Appels 1</div>'),
    $('<div class="fruit oranges">Oranges 2</div>')
  ]
  const random_element = elements[Math.floor(Math.random() * elements.length)]
  $('.element-placeholder').replaceWith(random_element);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element-placeholder"></div>
<!--This should be one of the .fruit divs instead of the text "pane_2"-->
mplungjan
  • 169,008
  • 28
  • 173
  • 236