Как закомментировать несколько строк в html
Перейти к содержимому

Как закомментировать несколько строк в html

  • автор:

Как гарантировано закомментировать любой кусок HTML ?

Возник интересный, и как выяснилось, нетривиальный вопрос. Необходимо вставить строки в html текст таким образом чтобы закомментировать произвольный блок с любым валидным содержанием.

Вариант 1. Пишем естественно:

И сразу облом: Разрешается внутрь комментария добавлять другие теги, вложенные комментарии (когда один комментарий расположен внутри другого) не допустимы.

Наш комментарий разрывается любым вложенным комментарием ( проверьте сами)!

Далее я нашел замечательный тег Оказалось он поддерживается только IE, поэтому даже не стал смотреть как он работает.

Последняя идея была такой:

Почти то что надо… до первого вложенного скрипта! Если внутри окажется то после закрывающего тега все оказывается раскомментированным.

How to comment/uncomment in HTML code

Often while coding view templates in html, my habit of adding some helpful comments causes lots of time-consuming effort while testing.

Consider this code.

Now, if I have to hide out some portion of the view template, in case of php I would just select the desired code and put single-line comments (using a shortcut key most of the times).

However, in html code, where only the block comments work, I end-up removing all the closing comment tags (—>) till the position I want the commenting to occur — something like this.

Then when I’m done testing I have to go through the agony of putting back those closing tags.

Is there a better and time saving way of block commenting in HTML?

11 Answers 11

Yes, to comment structural metadata out,

Using <script>/* . */</script> in .html

Comment out large sections of HTML (Comment Out Block)

my personal way in a .html file is opening: <script>/* and close it with */</script>

<script>/* hiding code go here */</script>

Is a workaround to the problem since is not HTML.

Considering your code in .html.

And in a case is HTML inside PHP file using comment tag <?/* or <?php /* and close it with */?> . Remember that the file must be .php extension and don’t work in .html.

<?/* hiding code go here */?>

Considering your code in .php.

Is worth nothing that is not HTML but a common developer practice is to comment out parts of metadata so that it will not be rendered and/or executed in the browser. In HTML, commenting out multiple lines can be time-consuming. It is useful to exclude pieces of template structural metadata containing comments, CSS or code and systematically commenting out to find the source of an error. It is considered a bad practice to comment blocks out and it is recommended to use a version control system. The attribute "type" is required in HTML4 and optional in HTML5.

HTML: How to Comment With Example

In this article HTML How to Comment we discussed How to comment out in HTML?, HTML comment syntax, and two or more examples where we use HTML comment in the document.

Basically, comments are helpful for web developers or designers to know about source code working which is encapsulated with some information about code using Comment Tag by any developer.

Here are the details which we discuss in this article,

  • Major points about HTML Comment Tag
  • HTML: How to Comment with Example
  • Browser Support

Major points about HTML Comment Tag

  1. The <!—. —> is an HTML Comment Tag.
  2. When you place content or information between <!—. —> this tag browser would not show these pieces of information.
  3. Developers can also hide the script tag code using HTML comments.
  4. Comment out HTML allows developers to leave notes or information about source code.

HTML: How to Comment with Example

The HTML comment encapsulate the piece of information by using comment tag.

Syntax

Single Line Comment

<! — This is a comment. Comments are not displayed in the browser →

<p>This is a paragraph.</p>

Multiline Comment

Sometimes we need to comment out multiple lines or some lines of code, then we use multiline comment.

<div>

<p>This text is visible. Check the source code for multi-line comment.</p>

<! —

Hello, world! I am a comment and I am

displayed in multiple lines!

</div>

You can also comment out or hide script code which is define inside <script> tag.

Note: You may also see <comment> tag somewhere but that comment tag is not supported by modern browsers.

HTML, как добавить комментарий

Чтобы добавить комментарий в HTML документ, используют специальный тег <!— comment —> .

Комментарии — это текст, который будет виден твоим коллегам, но не будет виден пользователям, загрузившим веб-страницу.

Или ты просто хочешь оставить себе напоминание, о том, что должно быть сделано.

Причин для таких сообщений довольно много, но все эти сообщения объединяет то, что они не должны отображаться на странице, а видны только в редакторе кода, который ты используешь.

Для комментариев не нужны специальные теги, но их нужно как-то обозначить чтобы было понятно, где начало комментария и где его окончание.

HTML комментарий из одной строки

Простейший комментарий состоит из одной строки. Текст нужно разместить между последовательностью символов <!— и —> :

Обрати внимание, что восклицательный знак ставится только в начале, но не в конце тега.

HTML комментарий из нескольких строк

Если тебе нужно добавить длинный комментарий, который состоит из нескольких строк, это тоже можно сделать в HTML.

Если внутри комментария будут расположены какие-то HTML теги, то их на странице видно не будет.

Ошибки

Ошибки в HTML комментариях чаще всего связаны с лишним пробелом или пропущенным восклицательным знаком:

Оба комментария написаны неправильно и будут отображаться на HTML странице.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *