1

I have a following code:

<div class="match">
  <div class="match-name">MATCH 1</div>
  <div class="match-league">LEAGUE 2</div>
</div>

<div class="match">
  <div class="match-name">MATCH 2</div>
  <div class="match-league">LEAGUE 1</div>
</div>

What I am trying to do is to scrape the data and the output should be an array of objects using this data-model:

{
  name: "match-name"
  league: "match-league"
}

I am not sure about the scraping part. How to loop through the divs and get the values?

5
  • Have you tried with: var divs = document.querySelectorAll(".match"); Commented Sep 9, 2019 at 21:40
  • yes, dont know how to extract name and league for match then tho :-( @Loki Commented Sep 9, 2019 at 21:42
  • are you looking for developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute Commented Sep 9, 2019 at 21:48
  • 1
    This is basic JavaScript. Selecting elements and reading their text or HTML. Commented Sep 9, 2019 at 21:49
  • If you still need this here is the jsfiddle.net/a7f5L0bc/22 with sample solution Commented Sep 9, 2019 at 21:56

2 Answers 2

1

You can use Array.prototype.map after converting the result of querySelectorAll to an Array using Array.from, and map each .match to an object of the desired format:

var matches = document.querySelectorAll('.match');

var arr = Array.from(matches).map(m => {
  let name = m.querySelector('.match-name').innerText,
      league = m.querySelector('.match-league').innerText;
      return {name : name, league : league}
});

console.log(arr);
<div class="match">
  <div class="match-name">MATCH 1</div>
  <div class="match-league">LEAGUE 2</div>
</div>

<div class="match">
  <div class="match-name">MATCH 2</div>
  <div class="match-league">LEAGUE 1</div>
</div>

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

Comments

0

Here is an example using querySelector API

const matches = document.querySelectorAll(".match")

console.log([...matches].map(match => ({
  name: match.querySelector(".match-name").innerText,
  league: match.querySelector(".match-league").innerText
})))
<div class="match">
  <div class="match-name">MATCH 1</div>
  <div class="match-league">LEAGUE 2</div>
</div>

<div class="match">
  <div class="match-name">MATCH 2</div>
  <div class="match-league">LEAGUE 1</div>
</div>

1 Comment

This doesn't do what the OP wants. Also, we tend not to answer questions where the OP hasn't even made an attempt at a solution. It just attracts more poor questions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.