使用查询选择器按ID

时间:2018-10-09 23:14:14

标签: javascript ios autocomplete shortcut queryselectall

我正在尝试创建一些简单的JavaScript来自动填充网页。

我想修改以下内容,以与用户名“ password_username”和密码“ password_password”的特定elementid一起使用

var result = [];

// Get all links from the page need to change to specific for username

var elements = document.querySelectorAll("input");
for (let element of elements) {
element.value = "username";
}

// Get all links from the page need to change to specific for password

var elements = document.querySelectorAll("input");
for (let element of elements) {
element.value = "password";
}

// Call completion to finish
completion(result) `

我才刚刚开始学习代码并且具有非常基本的javascript知识,感谢您的帮助!

干杯

垫子

2 个答案:

答案 0 :(得分:0)

希望我能正确理解您的问题。

要通过ID选择特定字段并为其设置值,可以使用document.querySelector("#the_id").value = "the_value";

如果您的对象具有{id:value}结构,则可以循环处理它:

const creds = {
  id1: 'val1',
  id2: 'val2' // ...
};

for (const [id, val] of Object.entries(creds)) {
  document.querySelector(`#${id}`).value = val;
}

请弄清楚我是否不明白您的需求,我们将很乐意为您提供帮助。

答案 1 :(得分:0)

不能完全确定它是否可以像我现在无法测试的那样工作,请尝试一下:

const usernameElements = document.querySelectorAll(`input[type="text"]`);
const passwordElements = document.querySelectorAll(`input[type="password"]`);

usernameElements.forEach(username => username.value = "the user name");
passwordElements.forEach(password => password.value = "the password");

它根据类型(文本/密码)选择输入字段,并将值添加到它们。现在,我不能完全确定您发布的内容是否是更大脚本的一部分,但这可能会满足您的需要。如果您想要不同的用户名和密码,则需要使usernamepassword变量能够动态加载,否则,将添加您为其提供的值,例如username.value = "testing username"password.value = "testing password"。干杯。

相关问题