EN
JavaScript / XPath - get input by name
10
points
In this short article we would like to show how to get input element by name attribute using XPath in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<form>
<label>Username:</label>
<input name="username" value="John" />
</form>
<script>
var result = document.evaluate('//input[@name="username"]', document.body);
var input = result.iterateNext();
if (input) {
console.log(input.value);
}
</script>
</body>
</html>