2017-09-08 2 views
2

배열/목록의 모든 값을 한 줄로 가져 오는 방법은 무엇입니까? HTML의반복 목록의 모든 값 가져 오기

예제 코드 :

<div class="projects"> 
    <span clas="project_title"> project1 </span> 
    <span clas="project_title"> project2 </span> 
</div> 

내가 범위의 값을하려면 나는이

document.querySelectorAll('div.projects span.project_title')[0].textContent 

결과 사용해야합니다 :

프로젝트 1을


document.querySelectorAll('div.projects span.project_title')[1].textContent 

결과 :

프로젝트 2


이로 반복 할 필요없이 결과를 수행하기 위해 어떤 간단한 JS 쿼리가 있는가하여 명부?

예 결과 :

프로젝트 1, 프로젝트 2


+0

아니, 목록이 방식 으로든, 반복되어야한다과 그 때는 join(',') 배열 배열을 만드는 데 사용. – Teemu

+0

@Teemu가 말한 것을 덧붙이면 : 목록을 반복하고 원하는 방식으로 출력하는 작은 함수를 만들지 못하게하는 것은 없습니다. – Jordumus

답변

3

방법은 반복하지 않고 그들 모두를 얻을 수 없다. 하지만 그 반복은 두포에서 수행 될 수 있습니다. Array#map을 사용하면 textContents을 얻을 수 있습니다. 이 경우 Array#map의 두포에서 수행되는 HTMLElements을 반복해야합니다.

const spans = document.querySelectorAll('div.projects span.project_title'); 
 
const texts = Array.prototype.map.call(spans, item => item.textContent); 
 

 
console.log(texts);
<div class="projects"> 
 
    <span class="project_title"> project1 </span> 
 
    <span class="project_title"> project2 </span> 
 
</div>

+0

새로운 ESnext 기능을 사용하는 것으로 보았을 때,'Array.prototype.map.call' 대신'Array.from'을 할 수 없습니까? – Keith

+0

@Keith 그런 이유로 왜 여분의 배열을 만들어야합니까? –

+0

'map'에'this'의 기능을 사용하고 있습니다. –

1

당신은 class와 스팬 클래스 속성 단어를 변경 .And Array.prototype.slice.call 방법으로 할 수 있습니다. Array#map이 항목의 내용을 얻기 위해, ,

var a = Array.prototype.slice.call(document.querySelectorAll('div.projects span.project_title')).map(a => a.textContent); 
 

 
console.log(a.join(','))
<div class="projects"> 
 
    <span class="project_title"> project1 </span> 
 
    <span class="project_title"> project2 </span> 
 
</div>