How to use javascript var with # sign to point id?

advertisements

How to use javascript var with # signature to point id ?

I tried to use $("#test_input_val").remove(); as same as $("#555").remove(); but not work.

https://jsfiddle.net/L1dx3nLb/2/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
    var test_input_val = document.getElementById("test_input").value;
        $("#test_input_val").remove();
    });
});
</script>

<body>

<input id="test_input" value="555"/>
<div id="555">test test test test test</div>
<br>

<button>Remove div element</button>

</body>


Since test_input_val is a variable, You need to concatenate and create a valid selector. then various operation can be performed.

 $("#" + test_input_val).remove();

As per current implementation is looking for element with id test_input_val, hence operation is not performed.

$(document).ready(function() {
  $("button").click(function() {
    var test_input_val = document.getElementById("test_input").value;
    $("#" + test_input_val).remove();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="test_input" value="555" />
<div id="555">test test test test test</div>
<br>

<button>Remove div element</button>