Adrien Brunelat Adrien Brunelat - 7 months ago 10
HTML Question

How to find HTML elements with values contained in a given array?

Problem



Given this piece of code:

<ul>
<li><input type="hidden" value="1"/>Choice 1</li>
<li><input type="hidden" value="2"/>Choice 2</li>
<li><input type="hidden" value="3"/>Choice 3</li>
<li><input type="hidden" value="4"/>Choice 4</li>
<li><input type="hidden" value="5"/>Choice 5</li>
</ul>


How can I properly select list elements that has an input with a value contained in the array
[1, 3, 4]
?




Research track



I tried some solutions in this code snippet, but nothing seems to work nicely.



alert($("li").has("input[value='3']").text()); // Not a solution
alert($("li").has("input[value='[1,3,4]']").text()); // Not working
alert($("li").has("input[value=[1,3,4]]").text()); // Not working
alert($("li").has("input[value=['1','3','4']]").text()); // Nope

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><input type="hidden" value="1"/>Choice 1</li>
<li><input type="hidden" value="2"/>Choice 2</li>
<li><input type="hidden" value="3"/>Choice 3</li>
<li><input type="hidden" value="4"/>Choice 4</li>
<li><input type="hidden" value="5"/>Choice 5</li>
</ul>




Answer

You could use filter() to find the li from the relevant child input elements.

var valueArr = [1, 3, 4];
var $li = $('li').filter(function() {
  return valueArr.indexOf(parseInt($(this).find('input').val(), 10)) != -1;
});
$li.css('color', '#C00'); // just to make the effect obvious
console.log($li.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <input type="hidden" value="1" />Choice 1</li>
  <li>
    <input type="hidden" value="2" />Choice 2</li>
  <li>
    <input type="hidden" value="3" />Choice 3</li>
  <li>
    <input type="hidden" value="4" />Choice 4</li>
  <li>
    <input type="hidden" value="5" />Choice 5</li>
</ul>