I'm struggling a bit with how to do a simple selection of a specific element in a element array in JavaScript. Consider the following:
var htmlString = "<span>someText</span><input type='hidden' class='idBox' name='id' data-id='6026' value='6026'>";
var eleArray = $.parseHTML(htmlString);
var inputVal = $(eleArray[1]).val();
inputVal
will hold the value of the input field. In this specific case it would be hold 6026.. However I don't like the way I get this value by selecting index 1 in the eleArray
, which is the input element. I would like to select it by the input elements id, which in this case by class would be idBox
or name id
.. But I don't know how to do that.
Any advice ?
CodePudding user response:
You can use the class selector syntax :
const htmlString = "<span>someText</span><input type='hidden' class='idBox' name='id' data-id='6026' value='6026'>";
$($.parseHTML(htmlString)).filter(".idBox").val();
// => '6026'
Other solution using the input name :
const htmlString = "<span>someText</span><input type='hidden' class='idBox' name='id' data-id='6026' value='6026'>";
$($.parseHTML(htmlString)).filter("input[name='id']").val();
CodePudding user response:
parseHTML
will give you an array of elements which you can use with jQuery, so you can filter
in the usual way you would with elements added to the DOM:
var htmlString = "<span>someText</span><input type='hidden' class='idBox' name='id' data-id='6026' value='6026'>";
var eleArray = $.parseHTML(htmlString);
var inputVal = $(eleArray).filter("[name='id']").val()
console.log(inputVal);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>