0

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 ?

3
  • Put the elements in the array to a document fragment. Commented Dec 7, 2021 at 10:22
  • did you try document.getElementById() to retrieve your element based on its id? Commented Dec 7, 2021 at 10:24
  • 2
    @Pochwar the elements are not in document - they won't be found when searching the DOM. Commented Dec 7, 2021 at 10:26

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.