jQuery与文档类型缩减之前输出的文本进行交互

时间:2018-12-29 04:05:54

标签: javascript php jquery dom

我有一个正在输出PHP通知的PHP应用程序。这是文本,在包括DOCTYPE声明在内的所有其他内容之前,都只是在浏览器中弹出。

    <br />
    <b>Notice</b>:  Undefined property: bla bla blap</b> on line <b>16</b><br />
    <!DOCTYPE html>
...regular web page

是否有一种使用jQuery与此文本进行交互的方法?它在浏览器中显示为第一件事。您如何在jQuery中选择<!DOCTYPE html>上方的内容?

1 个答案:

答案 0 :(得分:1)

您可以使用$('body').contents()访问这些元素,因为浏览器会将它们解释为正文的元素。当浏览器在doctype声明之前看到文本时,即使html无效,它也会将文本和头部内容转移到正文中,以尝试构建可行的DOM。

由于浏览器已经重新组织了内容,所以您无法猜测头部的第一个元素应该是什么。该脚本使您可以设置应该是头部的第一个元素的元素。然后,脚本将在设置元素之前访问元素,并为您提供有关该元素是文本节点还是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>