anson920520 anson920520 - 7 months ago 9
HTML Question

check if element has something

First, I receive a row of data from JSON and print the data on the HTML like

<p id="checker">1+2</p>


and below i have some checkboxes

<p style="display:none" id="1">cat</p>
<p style="display:none" id="2">dog</p>
<p style="display:none" id="3">fish</p>


And I'd like to make some p tags appear if the if statement is true

if ($("#checker").html() == "1") {
$("#1").css("display", "block");
}

elseif($("#checker").html() == "2") {
$("#2").css("display", "block");
}


but I realized that this can't satisfy my need.
Is there another solution for this task?

Answer

Split the string and iterate over them, based on the value get element and show.

$('#checker')
  .html() // get html content
  .split('+') // split string by +
  .forEach(function(v) { // iterate over them
    $('#' + $.trim(v)).show() // get element by id and show
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="checker">1+2</p>
<p style="display:none" id="1">cat</p>
<p style="display:none" id="2">dog</p>
<p style="display:none" id="3">fish</p>