Javascript:将用户名列表提取到控制台/文件

时间:2018-09-17 10:15:22

标签: javascript html

如何使用javascript将所有用户名类的内容列表提取到控制台,或者最好是文件?

.user-id, .username, .user-year { display: inline; }
<div id="#main">
  <div class="user-id">5</div>
  <div class="username">@user1</div>
  <div class="user-year">2018</div>
  <br>
  <div class="user-id">6</div>
  <div class="username">@user2</div>
  <div class="user-year">2015</div>
  <br>
  <div class="user-id">5</div>
  <div class="username">@user3</div>
  <div class="user-year">2012</div>
</div>

2 个答案:

答案 0 :(得分:5)

只需使用querySelectorAll('.username')选择它们,然后使用.map textContent

let users = [...document.querySelectorAll('.username')].map(i => i.textContent)

console.log(users)
.user-id, .username, .user-year { display: inline; }
<div id="#main">
  <div class="user-id">5</div>
  <div class="username">@user1</div>
  <div class="user-year">2018</div>
  <br>
  <div class="user-id">6</div>
  <div class="username">@user2</div>
  <div class="user-year">2015</div>
  <br>
  <div class="user-id">5</div>
  <div class="username">@user3</div>
  <div class="user-year">2012</div>
</div>

答案 1 :(得分:2)

您可以使用javscript和以下代码

var users= document.getElementsByClassName('username');

var users= document.getElementsByClassName('username');

for(i=0;i<users.length;i++){
console.log(users[i].innerText)
}
.user-id, .username, .user-year { display: inline; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="#main">
  <div class="user-id">5</div>
  <div class="username">@user1</div>
  <div class="user-year">2018</div>
  <br>
  <div class="user-id">6</div>
  <div class="username">@user2</div>
  <div class="user-year">2015</div>
  <br>
  <div class="user-id">5</div>
  <div class="username">@user3</div>
  <div class="user-year">2012</div>
</div>