Skip to content Skip to sidebar Skip to footer

How To Store Each Paragraph Into An Javascript Array When Onclick Event Occurs?

I have tried the following code. When the user clicks on any paragraph then this paragraph must be stored into a javascript array. If I clicked another paragraph then it must also

Solution 1:

  • Your loop is missing ;i++
  • You are pushing test[i] to itself. That does not sound right

I believe you wanted to do this - I copied your HTML from another question you wrote. NOTE I cannot test the paragraph anymore since you have other tags in the paragraph

window.addEventListener("load", function() {
  var test = [];
  [...document.querySelectorAll(".container p")].forEach(function(para) {
    para.addEventListener("click", function(e) {
      var text = e.currentTarget.textContent;
      if (test.indexOf(text) === -1) test.push(text); // or !test.includes(text) (not IE)
      else alert("Already added");
      console.log(test)
    })
  })
})
#container p {
  cursor: pointer;
  text-decoration: underline;
}
<div class="container">
  <p>
    <b>Group:N</b>Code:1234<br/>
    <b>Session Type:</b>CS<br/>
    <b>Location:</b>Main Hall<br/>
    <b>Time:</b>14:00<br/>
    <b>Day:</b>Tuesday<br/>
    <b>Duration:</b>1hour<br/>
  </p>
</div>
<div class="container">
  <p>
    <b>Group:M</b>Code:98743<br/>
    <b>Session Type:</b>NP<br/>
    <b>Location:</b>Main Hall2<br/>
    <b>Time:</b>11:00<br/>
    <b>Day:</b>Monday<br/>
    <b>Duration:</b>1hour<br/>
  </p>
</div>

Solution 2:

Using anchor tag (a) useless here which is not designed for this purpose. You can implement onclick attribute directly to p tag. If you want to call makeSelection function for each p tag, you don't need to iterate.

You can simply do this:

for JS:

let data = [];
function makeSelection(text) {
    data.push(text.textContent);
    console.log(data);
}

for HTML:

    <p onclick="makeSelection(this);">TEST1</p>
    <p onclick="makeSelection(this);">TEST2</p>
    <p onclick="makeSelection(this);">TEST3</p>

Solution 3:

Please try this.

function makeSelection(e) {
  let item = document.querySelectorAll('a');
  console.log(item);
  var test = [];
  for (var i = 0; i < item.length; i++) {
    test.push(item[i].children[0].textContent)
  }
  console.log(test)
}
<a href="#" onclick="makeSelection(this)">
  <p>This is p1</p>
</a>
<a href="#" onclick="makeSelection(this)">
  <p>This is p2</p>
</a>
<a href="#" onclick="makeSelection(this)">
  <p>This is p3</p>
</a>

Post a Comment for "How To Store Each Paragraph Into An Javascript Array When Onclick Event Occurs?"