Javascript:检查页面是否包含特定的 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4861017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:08:42  来源:igfitidea点击:

Javascript: Check if page contains a particular div

javascripthtmlhtml-parsing

提问by Skizit

How do I check using javascript if the page I'm on contains a particular div... e.g turtles

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

回答by niksvp

if(document.getElementById("divid")!=null){
  alert('Div exists')
}

回答by BiAiB

if you have that div's id, you can do it that way:

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

var myDiv = document.getElementById( 'turtles' );

if ( myDiv ) {
    //It exists
}

overwise, if it's a class, you'd better use a framework (jQuery here):

过度,如果它是一个类,你最好使用一个框架(这里是 jQuery):

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

回答by Elliot B.

I'd just like to point out that document.containsis another way to do this.

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

document.containsis particularly useful if you have a web application whose components are rendered virtually before insertion into the DOM.

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

回答by Shadow Wizard is Ear For You

Like this:

像这样:

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

The function must be located in bottom of page or called after page finished loading.

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