Вы можете получить доступ к элементам, используя $('body').contents()
, потому что браузер интерпретирует их как элементы тела.Когда браузер видит текст перед объявлением doctype, он смещает этот текст и содержимое заголовка в тело, пытаясь создать жизнеспособный DOM, даже если HTML-код недействителен.
Поскольку браузерреорганизовал контент, вы не можете догадаться, каким должен был быть первый элемент главы.Этот скрипт позволяет вам установить элемент, который должен был быть первым элементом головы.Затем скрипт получит доступ к элементам до того, который вы установили, и предоставит вам информацию о том, является ли элемент текстовым узлом или элементом DOM.
Вам нужно взаимодействовать с текстовыми узлами с помощью vanilla js, но вы можете использоватьJQuery для остальных.
// the script needs to know what should have been the first element in the head
const firstElementInHead = $( 'title' );
// remove all nodes prior to the intended content
$('body').contents().each( function() {
if ( $(this).index() < firstElementInHead.index() ) {
$(this).remove();
}
});
<br />
<b>Notice</b>: Undefined property: bla bla blap on line <b>16</b><br />
<!doctype html>
<html lang="en">
<head>
<title>The Broken Page</title>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
// the script needs to know what should have been the first element in the head
const firstElementInHead = $('title');
// log the nodes that apear prior to the intended content
$('body').contents().each(function() {
if ($(this).index() < firstElementInHead.index()) {
if (this.nodeType == Node.TEXT_NODE) {
console.log('This is a text node. You can change it by setting this.nodeValue, remove it by calling this.remove(), or other vanilla JS operations.');
console.log(this);
} else {
console.log('This is a DOM element. You can interact with it using jQuery the same way you interact with any normal DOM element.');
console.log(this);
}
}
});
</script>
</head>
<body style="padding:0; margin:0;">
<p style="padding:0; margin:0; background:red;">Test</p>
</body>
</html>