Reputation: 1
To get the html response of the page, I use:
var theUrl = "https://example.com/users/22";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send();
var html = xmlHttp.responseText;
This will now return a 535 line html page. If we simply had that source code on our current page, to get the value of the tag (12345) as shown below:
<input name="token" type="hidden" value="12345" />
we would simply use:
document.getElementsByName("token")[0].value;
But since the HTML is in the ajax response as a variable named html
how do I get the value of the input with name token? Can I somehow convert it to a DOM element and then run that code?
javascript only please, no jQuery.
Thanks.
Upvotes: 0
Views: 3879
Reputation: 1715
You can parse your xmltHttp.response text like this:
var xmlString = "<input name='token1' type='hidden' value='12345' />"; // Use your xmlHttp.responseText here. This is for demonstration purposes
var parser = new DOMParser();
var element = parser.parseFromString(xmlString, "text/html");
console.log(element.querySelectorAll('[name="token1"]')[0].value);
Upvotes: 1
Reputation: 1715
Try creating an HTML element, adding the response, and then parse it. We need to add a class name to select specific inputs with getElementsByClassName, or, if you want to select all inputs, you could use getElementsByTagName
var responseText = '<input name="token" class="token" type="hidden" value="12345" />'
var el = document.createElement( 'html' );
el.innerHTML = responseText;
console.log(el.getElementsByClassName("token")[0].value);
Upvotes: 2