1

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>
2
  • Does this answer your question? html "data-" attribute as javascript parameter Commented Mar 5, 2020 at 18:06
  • 2
    There's no id="usernamefield" attribute in your HTML, what is getElementById() supposed to find? Commented Mar 5, 2020 at 18:09

2 Answers 2

4

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">

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

1 Comment

OP's problem starts earlier. Their element has no id="usernamefield" so getElementById('usernamefield') cannot find it.
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

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.