Getting value of a class

This question already has an answer here:

Why can i get an id value with # but cant get a class value with . ex: $(button#${value}).val() --> works

$(button.${value}).val() --> doesn't work.

Answers 1

  • When your button element does not have a value property, val() will return the empty string.

    But if you put a value attribute to your button element it works, as this snippet demonstrates:

    var valueA = "a", valueB = "b";
    console.log($(`button#${valueA}`).val());
    console.log($(`button.${valueB}`).val());
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="a" class="b" value="hello">click</button>

    Or, if you take for instance the button's text (.text()), then also it works:

    var valueA = "a", valueB = "b";
    console.log($(`button#${valueA}`).text());
    console.log($(`button.${valueB}`).text());
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="a" class="b" value="hello">click</button>


Related Articles