0

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.

1

2 Answers 2

2

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

Getting: Uncaught TypeError: el.getElementsByName is not a function.
Looks like you can only call getElmentsByName on the document. We can call getElemetnsByClassName though on the response
1

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

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.