I currently have the following html within a pre-code block:
<pre class="prettyprint"><code> <html> <body> <form name="input" action="html_form_action.asp" method="get"> <input type="radio" name="sex" value="male">Male<br> <input type="radio" name="sex" value="female">Female<br> <input type="submit" value="Submit"> </form> <p>If you click the "Submit" button, the form-data will be sent to a page called "html_form_action.asp".</p> </body> </html> </code></pre>
It is indented within the html source for better structure within the document. How can I remove the leading whitespace? Through the use of javascript or is there a more simple method.
Home Indentation and Spacing in HTML In HTML, each nested tag should be indented exactly once inside of its parent tag. Place a line break after every block element. Do not place more than one block element on the same line.
Whitespace is any string of text composed only of spaces, tabs or line breaks (to be precise, CRLF sequences, carriage returns or line feeds).
So, while the default in HTML is to ignore multiple spaces and line breaks, you can override this using the <pre> tag. (X)HTML also allows the use of the non-breaking space ( ).
Whitespace refers to characters which are used to provide horizontal or vertical space between other characters. Whitespace is often used to separate tokens in HTML, CSS, JavaScript, and other computer languages.
The question asks if there's a JavaScript solution or a simpler method for removing leading whitespace. There's a simpler method:
CSS
pre, code { white-space: pre-line; }
DEMO
white-space
The
white-space
property is used to describe how whitespace inside the element is handled.pre-line
Sequences of whitespace are collapsed.
I really like Homam's idea, but I had to change it to deal with this:
<pre><code><!-- There's nothing on this line, so the script thinks the indentation is zero --> foo = bar </code></pre>
To fix it, I just take out the first line if it's empty:
[].forEach.call(document.querySelectorAll('code'), function($code) { var lines = $code.textContent.split('\n'); if (lines[0] === '') { lines.shift() } var matches; var indentation = (matches = /^[\s\t]+/.exec(lines[0])) !== null ? matches[0] : null; if (!!indentation) { lines = lines.map(function(line) { line = line.replace(indentation, '') return line.replace(/\t/g, ' ') }); $code.textContent = lines.join('\n').trim(); } });
(I'm also processing <code>
tags instead of <pre>
tags.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With