How to update a div by class and data attribute

I am trying to update a div by selecting its class name and data attribute, where the attribute value is a variable. The other SO answers (to similar questions) suggested this approach:

$(".SampleClass [id='"+selectedId + "']").text("Updated text");

When testing it out, however, it does not appear to work. What should happen is that the content of the second div should read "This specific div has been updated". Instead the div contains "Div 2 is unchanged".

What approach should I use to achieve the desired result? This example is simple HTML, but I am trying to apply this into a dynamic page -- which is why I'm not hard-coding it.

<div class="SampleClass" data-id="1">Div 1 is unchanged</div>
<div class="SampleClass" data-id="2">Div 2 is unchanged</div>
<div class="SampleClass" data-id="3">Div 3 is unchanged</div>

<script type="text/javascript" src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
    $(function () {
        // test basic functionality: div with data-id=2 should be updated 

        var selectedId = 2;  
        $(".SampleClass [id="+selectedId + "]").text("This specific div has been updated.");
    });
</script>

Answers 1

  • var selectedId = 2;
    $(".SampleClass[data-id=" + selectedId + "]").text("This specific div has been updated.");
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="SampleClass" data-id="1">Div 1 is unchanged</div>
    <div class="SampleClass" data-id="2">Div 2 is unchanged</div>
    <div class="SampleClass" data-id="3">Div 3 is unchanged</div>

    1. No space between .SampleClass[data-id=" + selectedId + "] if you put space it means child of class .SampleClass with data attribute id.
    2. Use data-id selector not id

Related Articles