【问题标题】:Javascript: Check if page contains a particular divJavascript:检查页面是否包含特定的 div
【发布时间】:2011-06-19 03:53:15
【问题描述】:

如果我所在的页面包含特定的 div,我如何使用 javascript 检查...例如 turtles

【问题讨论】:

  • turtles 是 id 还是 class?
  • 我想看看是不是

标签: javascript html html-parsing


【解决方案1】:
if(document.getElementById("divid")!=null){
  alert('Div exists')
}

【讨论】:

    【解决方案2】:

    如果你有那个 div 的 id,你可以这样做:

    var myDiv = document.getElementById( 'turtles' );
    
    if ( myDiv ) {
        //It exists
    }
    

    如果是类,最好使用框架(这里是jQuery):

    if ( $('.turtles').length > 0 ) {
      //it exists
    }
    

    【讨论】:

      【解决方案3】:

      像这样:

      <script type="text/javascript">
      function CheckExists() {
        var oDiv = document.getElementById("turtles");
        if (oDiv) {
          alert("exists");
        }
        else {
          alert("does not exist");
        }
      }
      </script>
      

      该函数必须位于页面底部或在页面加载完成后调用。

      【讨论】:

        【解决方案4】:

        我只想指出document.contains 是另一种方法。

        document.contains 如果您有一个 Web 应用程序,其组件在插入 DOM 之前虚拟呈现,则特别有用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-07-14
          • 1970-01-01
          • 2011-07-15
          • 2015-08-15
          • 2012-03-26
          • 1970-01-01
          • 1970-01-01
          • 2017-11-10
          相关资源
          最近更新 更多