Search code examples
jqueryvariablesconcatenationselector

How to add a variable to a selector that is already concatenated?


i am trying to get the data-lvl from a div and use it in a button's data i can't figure out how to put the variable dataquestion inside the selector knowing that the selector itself is already concatenated

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id='result'></div>

<div class='question' data-question='5' data-lvl='2'>

</div>


<script>
$(document).ready(function(){
  dataquestion=5;

  $('#result').html(<button type='button' data-lvl='"+$('.question[data-question="+ dataquestion +"]').data('lvl') +"[option]'>lorem ipsum</button>');
});
</script>

Solution

  • Your logic is correct, the issue is simply that the string concatenation is broken by the mis-matched quotes. Try this:

    $(document).ready(function() {
      let dataquestion = 5;
    
      $('#result').html('<button type="button" data-lvl="' + $('.question[data-question="' + dataquestion + '"]').data('lvl') + '[option]">lorem ipsum</button>');
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
    <div id="result"></div>
    <div class='question' data-question="5" data-lvl="2"></div>

    Also note that you could use Template literals to make the string concatenation slightly more succinct, assuming you don't need IE support:

    $('#result').html(`<button type="button" data-lvl="${$('.question[data-question="' + dataquestion + '"]').data('lvl')}[option]">lorem ipsum</button>`);