bir div'deki satır sayısını saymanın ve ilk çift satırın textContent'ini almanın bir yolu var mı?

Jan 08 2021

Amacım, bir div'deki ilk 3 satırın metnin uzunluğunu elde etmektir. Ör:

<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'de bulunan satırların sayısını şu şekilde sayabiliyorum:

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

ancak yukarıdaki durumda ilk 3 satırın metninin uzunluğunu bulmanın bir yolu olup olmadığını bilmek istiyorum:

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

diyelim ki yapıyorum:

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

bu javascript'te mümkün mü?

Yanıtlar

2 WiatroBosy Jan 08 2021 at 15:42

JQuery'de istiyorsanız

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 sonu

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>