数组来自页面上特定类的所有元素的内容

时间:2018-05-01 12:52:38

标签: javascript html

我们正在建立一个免费的数据库,我得到了一些无聊的复制粘贴工作,我想加快一点。

我想创建一个HTML页面,当它提供一个链接时,会得到一个链接页面的某些类内所有内容的数组。我想要从中提取信息的所有页面都使用相同的类名称。

它们看起来像这样:

<ul class="section">
    <li class="article">
        <div class="author">
            <span class="FamilyName">Author1's Family Name </span>
            <span class="GivenName">Author1's Given Name</span>: 
        </div>
        <div class="titles">
            <a href="url_to_work.htm" title="Click here to read">
            <span class="title">Title of Work 1</span>
            </a>
        </div>
    </li>
</ul>

<ul class="section">
    <li class="article">
        <div class="author">
            <span class="FamilyName">Author2's Family Name </span>
            <span class="GivenName">Author2's Given Name</span>: 
        </div>
        <div class="titles">
            <a href="url_to_work.htm" title="Click here to read">
            <span class="title">Title of Work 2</span>
            </a>
        </div>
    </li>
</ul>

所以基本上我想得到一组作者&#39;全名,另一部作品&#39;标题(&#34;标题&#34;跨度)。像:

names = ["Author1's Family Name", "Author1's Given Name", "Author2's Family Name", "Author2's Given Name" ... etc.]
titles = ["Title of Work 1", "Title of Work 2", ... etc.]

从那里,我可以制作我想要的清单。

HTML&amp; JS?

1 个答案:

答案 0 :(得分:0)

使用document.querySelectorAll&amp; innerHTML。使用document.querySelectorAll获取课程.sections的所有元素。使用forEach对其进行迭代 您可以使用密钥familyNamegivenName以及密钥id创建一个对象数组。此id将用于从titleArray

获取相关标题

var getAllSection = document.querySelectorAll('.section');
var nameArray = [];
var titleArray = [];
getAllSection.forEach(function(item, index) {
  let obj = {
    familyName: item.querySelector('.FamilyName').innerHTML.trim(),
    givenName: item.querySelector('.GivenName').innerHTML.trim(),
    id: index
  }
  let obj2 = {
    title: item.querySelector('.title').innerHTML.trim(),
    id: index
  }
  nameArray.push(obj);
  titleArray.push(obj2)
});
console.log(nameArray, titleArray)
<ul class="section">
  <li class="article">
    <div class="author">
      <span class="FamilyName">Author1's Family Name </span>
      <span class="GivenName">Author1's Given Name</span>:
    </div>
    <div class="titles">
      <a href="url_to_work.htm" title="Click here to read">
        <span class="title">Title of Work 1</span>
      </a>
    </div>
  </li>
</ul>

<ul class="section">
  <li class="article">
    <div class="author">
      <span class="FamilyName">Author2's Family Name </span>
      <span class="GivenName">Author2's Given Name</span>:
    </div>
    <div class="titles">
      <a href="url_to_work.htm" title="Click here to read">
        <span class="title">Title of Work 2</span>
      </a>
    </div>
  </li>
</ul>