'JavaScript get element value in Input by jsname
I'm trying to scrape data from an html file. Specifically, I need the value of a variable in an input. Below I have an example of an input and what I have tried to do so far (I am specifically trying to get the "data-inital-value:
Input:
<input type="username" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="current-username" spellcheck="false" tabindex="0" aria-label="Enter your username" name="usernamefield" autocapitalize="off" dir="ltr" data-initial-dir="ltr" data-initial-value="trying to get this" badinput="false">
My code:
<script>
String uname = document.getElementById('usernamefield').value
</script>
Solution 1:[1]
You can use getAttribute
Note: document.getElementById('usernamefield') to select the input element but there is id attribute on that input element. Either add the id or select using any other way.
const input = document.querySelector('input')
console.log(input.getAttribute('data-initial-value'))
<input type="username" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="current-username" spellcheck="false" tabindex="0" aria-label="Enter your username" name="usernamefield" autocapitalize="off" dir="ltr" data-initial-dir="ltr" data-initial-value="trying to get this" badinput="false">
As the attribute you need is prefixed with data you can get it using dataset. Note that when you will use dataset the property name will be converted to camelCase. For example initial-value will be converted to initalValue
const input = document.querySelector('input')
console.log(input.dataset.initialValue)
<input type="username" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="current-username" spellcheck="false" tabindex="0" aria-label="Enter your username" name="usernamefield" autocapitalize="off" dir="ltr" data-initial-dir="ltr" data-initial-value="trying to get this" badinput="false">
Solution 2:[2]
This is a bit late, but for everyone who needs it.
Use can use the querySelector/querySelectorAll for it.
document.querySelector("div[jsname='something']")
You can also write in the [] every attribute you want like data-attributes.
Hope I can help something :D
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Kes |
