Меню

Ошибка start tag body seen but an element of the same type was already open

I validated my wordperes for my website and it came up with this problem, I tried to solve it but I keep failing. Can someone please explain to the problem and come up with a solution?

This is my header code:

<?php
/**
 * The header for our theme.
 *
 * Displays all of the <head> section and everything up till <div id="content">
 *
 * @package Sydney
 */
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
  (adsbygoogle = window.adsbygoogle || []).push({
    google_ad_client: "ca-pub-3232525101388979",
    enable_page_level_ads: true
  });
</script>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
<?php if ( ! function_exists( 'has_site_icon' ) || ! has_site_icon() ) : ?>
	<?php if ( get_theme_mod('site_favicon') ) : ?>
		<link rel="shortcut icon" href="<?php echo esc_url(get_theme_mod('site_favicon')); ?>" />
	<?php endif; ?>
<?php endif; ?>
<?php wp_head(); ?>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-W8PN789');</script>
<!-- End Google Tag Manager -->
<meta name="msvalidate.01" content="7791D9C1F13C9D493ACB1BAF76FD84DB" />
</head>
<body <?php body_class(); ?>>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-W8PN789"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<?php do_action('sydney_before_site'); //Hooked: sydney_preloader() ?>

<div id="page" class="hfeed site">
	<a class="skip-link screen-reader-text" href="#content"><?php _e( 'Skip to content', 'sydney' ); ?></a>
	<?php do_action('sydney_before_header'); //Hooked: sydney_header_clone() ?>
	<header id="masthead" class="site-header" >
		<div class="header-wrap">
            <div class="container">
                <div class="row">
				<div class="col-md-4 col-sm-8 col-xs-12">
		        <?php if ( get_theme_mod('site_logo') ) : ?>
					<a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php bloginfo('name'); ?>"><img class="site-logo" src="<?php echo esc_url(get_theme_mod('site_logo')); ?>" alt="<?php bloginfo('name'); ?>" /></a>
		        <?php else : ?>
					<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
					<h2 class="site-description"><?php bloginfo( 'description' ); ?></h2>	        
		        <?php endif; ?>
				</div>
				<div class="col-md-8 col-sm-4 col-xs-12">
					<div class="btn-menu"></div>
					<nav id="mainnav" class="mainnav" >
						<?php wp_nav_menu( array( 'theme_location' => 'primary', 'fallback_cb' => 'sydney_menu_fallback' ) ); ?>
					</nav><!-- #site-navigation -->
				</div>
				</div>
			</div>
		</div>
	</header><!-- #masthead -->
	<?php do_action('sydney_after_header'); ?>

	<div class="sydney-hero-area">
		<?php sydney_slider_template(); ?>
		<div class="header-image">
			<?php sydney_header_overlay(); ?>
			<img class="header-inner" src="<?php header_image(); ?>" width="<?php echo esc_attr( get_custom_header()->width ); ?>" alt="<?php bloginfo('name'); ?>"title="<?php bloginfo('name'); ?>" >
		</div>
		<?php sydney_header_video(); ?>

		<?php do_action('sydney_inside_hero'); ?>
	</div>

	<?php do_action('sydney_after_hero'); ?>

	<div id="content" class="page-wrap">
		<div class="container content-wrapper">
			<div class="row">
</div>
</body>

День добрый. Проверяю свой сайт на ошибки, дубли начали появляться ещё. Валидатор выдал это:
601a9cbcf195a702423059.jpeg
Не очень понятно, что они означают, особенно Fatal Error, и как их исправить.
Сам сайт на Битриксе, поэтому, ошибки могут тянуться и из php шаблонов.

Error: Bad start tag in div in noscript in head.

From line 84, column 11; to line 84, column 15

<noscript><div><img s

Error: Stray end tag noscript.

From line 84, column 119; to line 84, column 129

" /></div></noscript>↩<!-- 

Warning: The type attribute is unnecessary for JavaScript resources.

From line 87, column 1; to line 87, column 31

nter -->↩↩<script type="text/javascript">↩var _

Error: Stray end tag head.

From line 93, column 1; to line 93, column 7

script>↩↩↩</head>↩↩<bod

Error: Start tag body seen but an element of the same type was already open.

From line 95, column 1; to line 95, column 39

↩</head>↩↩<body class=" header_1 sidebar_left  ">↩   ↩↩

Fatal Error: Cannot recover after last error. Any further errors will be ignored.

From line 95, column 1; to line 95, column 39

↩</head>↩↩<body class=" header_1 sidebar_left  ">↩   ↩↩

Привет.  Сразу отвечу на ваш вопрос: стоит ли читать Вам этот урок? Перейдите на весьма полезный и бесплатный сервис validator.w3.org, вбейте туда адрес своего сайта и, если вы видите, что на Вашем сайте есть ошибки, то урок прочитать стоит. Примеры отображения ошибок с помощью данного онлайн валидатора:

На моем же блоге сейчас нет подобных ошибок, я от них избавился (всего было более 70 ошибок и более 80-ти предупреждений). Чтобы внести  ясность, расскажу, что такое валидный код и зачем он нам необходим.

Валидный код — это код, который соответствует стандартам.

На валидность можно проверить HTML, CSS, всяческие микроразметки и другое. Сегодня я расскажу про валидность в HTML.

  • Валидный код необязателен, но количество ошибок должно быть минимальным, иначе ваш сайт не будет кроссбраузерным. Валидность кода нужна в прежде всего для того, чтобы ваш сайт отображался правильно во всех браузерах.
  • Поисковые роботы «разговаривают» с вашим сайтом на языке HTML, поэтому важно отдавать четко и ясно контент на сайте со всеми «закрытыми тегами» и прочее.
  • Валидность HTML влияет на SEO, но довольно незначительно (если, конечно, у вас не сотни, а то и тысячи ошибок). Рекомендую почитать интересные наблюдения Деваки «Влияние качества HTML на их ранжирование».
  • Когда я делал на своем сайте код валидным, я нашел и исправил свои глупые ошибки (повторение тегов, пропущенная буква и т.п.).
  • Не стоит «рвать себе *опу», если какую-то ошибку сложно исправить, либо ее исправление принесет вред функциональности сайта. Главное, чтобы было удобно пользователю.

Ниже я разберу основные ошибки, на которые указывал валидатор. Если вдруг в списке ниже не окажется вашей ошибки, впишите ее в комментариях, попробуем вместе разобраться и я добавлю решение данной проблемы в данный урок. Кстати, да, ошибки, на которые указывает валидатор w3c смотрим тут:

В каждой ошибке есть подсказка — это номер строки в исходном коде странице, а из нее уже можно определить примерно в каком файле темы расположена данная строка. Исходный код страницы смотрим с помощью CTRL+U (в основных браузерах).

Перед тем, как приступить к работе, сделайте резервную копию шаблона вашего сайта.

Также для упрощения нахождения ошибок в исходном коде, можете использовать HTML валидатор для Mozilla Firefox. Установив его, перейдя в исходный код страницы, вы увидите те же самые ошибки, что указывает сервис validator.w3.org.  Кликнув по названию ошибки (в левом нижнем углу), вас автоматически перебросит на ту строчку, где находится данный невалидный код.

Нахождение ошибок в HTML с помощью валидатора w3c и их исправление

Ищите в списке ниже свою ошибку и кликнуть по ней, вас автоматически «прокрутит» куда надо.

  1. No space between attributes.
  2. The width attribute on the td element is obsolete. Use CSS instead.
  3. An img element must have an alt attribute, except under certain conditions. For details, consult guidance on providing text alternatives for images.
  4. Section lacks heading. Consider using h2-h6 elements to add identifying headings to all sections.
  5. The hgroup element is obsolete. To mark up subheadings, consider either just putting the subheading into a p element after the h1-h6 element containing the main heading, or…
  6. Element «noindex» undefined.
  7. End tag for element «div» which is not open
  8. Document type does not allow element «li» here; missing one of «ul», «ol», «menu», «dir» start-tag.
  9. End tag for «div» omitted, but OMITTAG NO was specified.
  10. There is no attribute «border».
  11. Character «<» is the first character of a delimiter but occurred as data.
  12. Saw » when expecting an attribute name. Probable cause: = missing immediately before.
  13. The align attribute on the img element is obsolete. Use CSS instead.
  14. Bad value Блог Алексея Смирнова for attribute href on element link: Illegal character in path segment: not a URL code point.

1. No space between attributes.

…rel=»shortcut icon» href=»http://arbero.ru/favicon.ico» ; type=»image/x-icon» Просто убираем «точку с запятой».

2. The width attribute on the td element is obsolete. Use CSS instead.

td valign=»center» width=»80″ height=»80″ >

Подобное преобразуем к виду

td style=»align:center; width:80; height: 80;»>

3. An img element must have an alt attribute, except under certain conditions. For details, consult guidance on providing text alternatives for images.

Одна из самых частых ошибок. Просто не хватает альтернативного текста для картинки. Прописываем тег alt.

4. Section lacks heading. Consider using h2-h6 elements to add identifying headings to all sections.

section id=»comments» >

Внутри блока section должны содержаться что-то из тегов h2-h6, если их нет, просто переименовываем слово section на div

 5. The hgroup element is obsolete. To mark up subheadings, consider either just putting the subheading into a p element after the h1-h6 element containing the main heading,

or else putting the subheading directly within the h1-h6 element containing the main heading, but separated from the main heading by punctuation and/or within, for example, a span class=»subheading» element with differentiated styling. To group headings and subheadings, alternative titles, or taglines, consider using the header or div elements.

Аналогично предыдущему пункту. Просто меняем фразу hgroup на div. Вы можете использовать инструмент «Найти/заменить все» в текстовом редакторе, чтобы ускорить подобные процессы.

6. Element «noindex» undefined

Чтобы тег noindex стал валидным, пишем его в виде комментирования, то есть так:

&lt;!--noindex--&gt;Неиндексируем&lt;!--/noindex--&gt;

7. End tag for element «div» which is not open

Закрывающий тег div лишний. Убираем его.

8. Document type does not allow element «li» here; missing one of «ul», «ol», «menu», «dir» start-tag

Неправильное использование тега «li»: отсутствует тег «ul», «ol» и др. Проверьте.

9. End tag for «div» omitted, but OMITTAG NO was specified

Не хватает закрывающего тега div.

10. There is no attribute «border»

alt=»» width=»1″ height=»1″ border=«0″/>

Просто удаляем фразу border=»0″.

11. Character «<» is the first character of a delimiter but occurred as data

Не используйте тег «<» перед обычными словами, используйте лучше разные кавычки.

12. Saw » when expecting an attribute name. Probable cause: = missing immediately before.

Лишняя кавычка, удалите ее.

13. The align attribute on the img element is obsolete. Use CSS instead.

Не используйте значение align внутри тега img. Пропишите ее отдельно, в таком виде:

&lt;div align='center'&gt;тут картинка (img src)&lt;/div&gt;

14. Bad value for attribute href on element link: Illegal character in path segment: not a URL code point.

То, что идет в href должно быть ссылкой, начинаться с http, но никак не слово.

Заключение

Если у вас на сайте есть какая-то ошибка, которой нет в этом списке — пишите в комментариях. Разберемся, а я дополню статью. Повторюсь, если какую-то ошибку не получается исправить, не стоит заморачиваться.

У меня на блоге осталась ошибка (хотя еще вчера почему-то код был без ошибок):

The text content of element script was not in the required format: Expected space, tab, newline, or slash but found < instead.

Если в курсе, как исправить ее, буду признателен. Я немножко перфекционист. 🙂

Будете ли вы делать HTML код сайта валидным?

Пожелаю вам получить валидный HTML код на вашем сайте, уведомление которого выглядит так:

P.s. Вы часто перегружаете свой организм? Тогда вам нужна программа детоксикации. Восстановите силы и энергетический баланс.

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Brendan Whiting

seal-mask

Stumped here. I whittled a copy of my code down to basically nothing to try and find the error but I can’t see it.

<!doctype html>
<html>
  <head>
    <title>Responsive Layout Demo</title>
  </head>
  <header>
  </header>
  <body>
  </body>
</html>

When I run this through the HTML5 Validator I get this error:

Error: Start tag body seen but an element of the same type was already open.
From line 8, column 3; to line 8, column 8
header>↩ <body>↩ </b

2 Answers

Tobias Helmrich

Hey Brendan,

I don’t know if that causes the problem but the header tags should be in the body.

David Abel February 5, 2016 10:36pm

As Tobias pointed out, your header should be inside the body tag.
Like this

<!doctype html>
<html>
  <head>
    <title>Responsive Layout Demo</title>
  </head>
  <body>
    <header>
    </header>
  </body>
</html>

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка start stop lexus
  • Ошибка start pxe over ipv6