div의 줄 수를 세고 첫 번째 몇 줄의 textContent를 얻는 방법이 있습니까?-Javascript [duplicate]

Jan 08 2021

내 목표는 div에서 처음 3 줄의 textContent 길이를 얻는 것입니다. 전의:

<div id="content" style="width: 100%;  
                line-height: 20px"> 
        <p>hello how are you?</p> 
        <p>hello how are you too?</p> 
        <p>hello how are you john? </p> 
        <p>hello how are you sphia?</p> 
    </div> 

다음을 사용하여 div에 포함 된 줄 수를 계산할 수 있습니다.

 function countLines() {
   var el = document.getElementById('content');
   var divHeight = el.offsetHeight
   var lineHeight = parseInt(el.style.lineHeight);
   var lines = divHeight / lineHeight;
   alert("Lines: " + lines);
}

그러나 위의 경우 처음 세 줄의 텍스트 길이를 찾는 방법이 있는지 알고 싶습니다.

 <p>hello how are you?</p> 
            <p>hello how are you too?</p> 
            <p>hello how are you john? </p> 

내가 할 말을 해보자.

var lines = countLines(); // 4
if (lines > 3) {
  test = document.getElementById("content").textContent.length;
// get the length of first 3 lines
}

자바 스크립트에서 가능합니까?

답변

2 WiatroBosy Jan 08 2021 at 15:42

jQuery에서 원하는 경우

let p = $('#content').find('p'); for (i = 0; i < 3; i++) { console.log($(p[i]).text().length);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" style="width: 100%;  
                line-height: 20px">
  <p>hello how are you?</p>
  <p>hello how are you too?</p>
  <p>hello how are you john? </p>
  <p>hello how are you sphia?</p>
</div>

끝 js

let p=document.getElementById("content");
let v=p.getElementsByTagName("p"); 
for (i = 0; i < 3; i++) {
  console.log(v[i].innerHTML.length);
}
<div id="content" style="width: 100%;  
                line-height: 20px">
  <p>hello how are you?</p>
  <p>hello how are you too?</p>
  <p>hello how are you john? </p>
  <p>hello how are you sphia?</p>
</div>