Counting lines, including html code after a specific line in a text using JavaScript

In this script, we first get the element containing the text using "document.getElementsByClassName()" and store it in a variable called "brl". We then split the text into an array of lines using "split("\n")" and count the number of lines using "length". We divide the result by two to determine where to insert our code.

Next, we define the code we want to inject using "var elem = "<hr>";" and replace the line of text at the specified position with the new content using "brl.innerHTML.replace()". Finally, we update the inner HTML of the element using "brl.innerHTML".

Note that you'll need to modify the JavaScript code to suit your specific needs, such as adjusting the location of the code injection or adding more complex logic.

<div class="post-body">
The first line of text
The second line of text
The third line of text
Fourth line of text
</div>
<script>
// get element containing the text
var brl=document.getElementsByClassName("post-body")[0];
var brl1=brl.innerHTML.split("\n");
//Count the number of lines in the text and divide the result by two to include your code in the middle of the text.
var brl2=Math.round(brl1.length/2)-1
//inser your code in the text
var elem="<hr>"

var brl3=brl.innerHTML.replace(brl1[brl2], brl1[brl2]+elem)
document.getElementsByClassName("post-body")[0].innerHTML=brl3
</script>
Counting lines, including html code after a specific line in a text using JavaScript,  JavaScript, text injection, code inclusion, line counting

© 2025 Manajmnt code

Share to :

Related

Comments