Выбор элемента узла в JavaScript

Я пытаюсь создать генератор цитат, и я пытаюсь взять цитаты из коллекции абзацев HTML.

Когда я пытаюсь получить доступ к случайному элементу списка узлов, я получаю все узлы в виде группы абзацев, а не только одного абзаца.

Это моя попытка рандомизатора:

const quotes = quotesdocument.querySelectorAll("p");

const randomize = function() {
  for(quote of quotes) {
    let num = (Math.floor(Math.random() * Math.floor(quotes.length)) - 1);
    console.info(quotes.item(num));
  }
}

А это отрывок из HTML, который я пытаюсь рандомизировать:

<p>&#8220;<a href = "https://theunboundedspirit.com/ananda-coomaraswamy-quotes/">Art</a> is the supreme task and the truly metaphysical activity in this life.&#8221;</p>
<p>&#8220;Underneath this reality in which we live and have our being, another and altogether different reality lies concealed.&#8221;</p>
<p>&#8220;We obtain the concept, as we do the form, by overlooking what is individual and actual; whereas nature is acquainted with no forms and no concepts, and likewise with no species, but only with an X which remains inaccessible and undefinable for us.&#8221;</p>
<p>&#8220;Everything which distinguishes man from the animals depends upon this ability to volatilize perceptual metaphors in a schema, and thus to dissolve an image into a concept.&#8221;</p>
<p>&#8220;Our destiny exercises its influence over us even when, as yet, we have not learned its nature: it is our future that lays down the law of our today.&#8221;</p>

Я ожидал, что получу только один из этих абзацев, но продолжаю получать их все.

Спасибо за помощь.

Просто убрать шлейф for? (и, вероятно, -1, иначе индекс иногда будет -1)

CertainPerformance 01.01.2019 23:04
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
1
35
2

Ответы 2

Причина, по которой он не работает, заключается в том, что вы повторяете все цитаты. Удаление цикла for и изменение логики рандомизации исправят это:

const quotes = document.querySelectorAll("p");

const randomize = function() {
  let num = Math.floor(Math.random() * quotes.length) - 1;
  console.info(quotes.item(num).innerText);
}

randomize();
<p>&#8220;<a href = "https://theunboundedspirit.com/ananda-coomaraswamy-quotes/">Art</a> is the supreme task and the truly metaphysical activity in this life.&#8221;</p>
<p>&#8220;Underneath this reality in which we live and have our being, another and altogether different reality lies concealed.&#8221;</p>
<p>&#8220;We obtain the concept, as we do the form, by overlooking what is individual and actual; whereas nature is acquainted with no forms and no concepts, and likewise with no species, but only with an X which remains inaccessible and undefinable for
  us.&#8221;</p>
<p>&#8220;Everything which distinguishes man from the animals depends upon this ability to volatilize perceptual metaphors in a schema, and thus to dissolve an image into a concept.&#8221;</p>
<p>&#8220;Our destiny exercises its influence over us even when, as yet, we have not learned its nature: it is our future that lays down the law of our today.&#8221;</p>

В приведенном выше фрагменте я console.info() устанавливаю текст внутри элемента, чтобы вы могли видеть, что он работает, но для доступа к самому элементу просто удалите innerText, который я там разместил.

Цикл for..of, который есть в вашем коде, не нужен. Просто используйте код, который у вас уже есть, и num в качестве значения индекса массива quotes. Я добавил кнопку, чтобы продемонстрировать, как функция возвращает только одно значение:

function randomQuote() {
  const quotes = document.querySelectorAll("p");
  const num = (Math.floor(Math.random() * Math.floor(quotes.length)));
  return quotes[num].innerText;
}

document.querySelector('#buttonEl').addEventListener('click', () => {
  document.querySelector('#quoteEl').innerHTML = randomQuote();
});
#quoteEl {
  color: red;
}
<input id = "buttonEl" type = "button" value = "Click for a random quote from the list below" />
<div id = "quoteEl"></div>
<p>&#8220;<a href = "https://theunboundedspirit.com/ananda-coomaraswamy-quotes/">Art</a> is the supreme task and the truly metaphysical activity in this life.&#8221;</p>
<p>&#8220;Underneath this reality in which we live and have our being, another and altogether different reality lies concealed.&#8221;</p>
<p>&#8220;We obtain the concept, as we do the form, by overlooking what is individual and actual; whereas nature is acquainted with no forms and no concepts, and likewise with no species, but only with an X which remains inaccessible and undefinable for
  us.&#8221;
</p>
<p>&#8220;Everything which distinguishes man from the animals depends upon this ability to volatilize perceptual metaphors in a schema, and thus to dissolve an image into a concept.&#8221;</p>
<p>&#8220;Our destiny exercises its influence over us even when, as yet, we have not learned its nature: it is our future that lays down the law of our today.&#8221;</p>

Другие вопросы по теме