Newb 4 You BB
Newb 4 You BB

Reputation: 1355

Adding Line Numbers To Pre-formatted Text

I have a body of text that I show in a web page within some <pre> tags. I would like to add a column to the left of this text body to show the line number of the text.

The body of text is retrieved by using [PHP] file_get_contents() so I am just echo-ing a string within the <pre> tags.

I imagine this can be accomplished with JavaScript but I have yet to find a solution.

Solutions I have seen on here usually use a library or CSS. The CSS method would be great but this method seems to require that each line of the body text have its own corresponding tag (eg <p> or <span>).

// Example of CSS Solution

p:not(:first-child):before {
  counter-increment: custom-counter+1;
  content: counter(custom-counter)". ";
  display: table-cell;
}
p:first-child:before {
  display: table-cell;
  content: '1. '
}

I would like to avoid having to create a DOM element (before load) line by line. That said, if that is the best solution I simply want to know the "preferred" way to go about this.

How could I accomplish this using JavaScript / jQuery?

Upvotes: 1

Views: 1081

Answers (1)

Samuel
Samuel

Reputation: 1152

One simple solution would be to split the string on "\n" with javascript to get each line append the line numbers then re-join them together. This will only work if you are using <pre> tags where newlines are literal newlines.

JsFiddle

    let text = document.getElementById("test").innerHTML;
    let lines = text.split("\n");
    for (let i=0;i<lines.length;i++) {
        lines[i] = (i+1)+" "+lines[i];
    }
    text = lines.join("\n");
    document.getElementById("test").innerHTML = text;

Upvotes: 1

Related Questions