@fuckingawesomenigga

Как собрать массив из атрибутов элементов?

<main>
    <form action="">
        <input type="text" name="qwe">
        <input type="text" name="asd">
        <input type="text" name="zxc">
    </form>
</main>


Как вытащить qwe,asd,zxc в массив?
  • Вопрос задан
  • 170 просмотров
Решения вопроса 2
Chefranov
@Chefranov
Новичок
$(document).ready(function() {
  var arr = [];
  $("form input").each(function() {
    arr.push($(this).attr("name"));
  });
  console.log(arr);
});
Ответ написан
Комментировать
0xD34F
@0xD34F Куратор тега JavaScript
Как получить input'ы:

const inputs = document.querySelectorAll('form input');
// или
const inputs = document.forms[0].elements;
// или
const inputs = document.querySelector('form').getElementsByTagName('input');

Как из input'а достать его name:

const getName = el => el.name;
// или
const getName = el => el.getAttribute('name');
// или
const getName = el => el.attributes.name.value;

Как собрать массив name'ов:

const names = Array.from(inputs, getName);
// или
const names = [].map.call(inputs, getName);
// или
const names = [];
for (const n of inputs) {
  names.push(getName(n));
}
// или
const names = [];
for (let i = 0; i < inputs.length; i++) {
  names[i] = getName(inputs[i]);
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы