检查元素是否具有id name的子节点

时间:2016-03-09 20:33:02

标签: javascript

如果这是一个简单的问题,我道歉!我对javascript很新。

我正在尝试检查div是否具有特定的子元素(我将其命名为'child2')。我知道.hasChildNodes()但据我所知它只会让你知道子节点是否存在。我试过像这样的.contains:

if (parentDiv.contains(child2) == false) {

但即使parentDiv 包含child2,它仍会返回false。这似乎是一件很简单的事情,我一直在尝试搜索,但我在纯粹的js中没有任何运气。谢谢!

2 个答案:

答案 0 :(得分:12)

您可以使用zoom=5 while True: where = raw_input('Where would you like a map of?') try: heatmap = folium.Map(location=geo(where), tiles='Stamen Toner', zoom_start=zoom) pointmap = folium.Map(location=geo(where), tiles='Stamen Toner', zoom_start=zoom) except AttributeError, GeocoderServiceError: print "Cannot create map with the given location. Please try again." else: break while True: zoom_level = {'city':9, 'state':7, 'country':5, 'world':9} zoom_detail = raw_input('What level of detail would you like: city, state, country, or world?') try: zoom = zoom_level[str(zoom_detail)] except TypeError, IndexError: print 'Please enter: city, state, country, or world. Try again' continue else: break heatmap = folium.Map(location=geo(where), tiles='Stamen Toner', zoom_start=zoom) pointmap = folium.Map(location=geo(where), tiles='Stamen Toner', zoom_start=zoom)

querySelector()

var hasChild = parentDiv.querySelector("#child2") != null; 方法允许您使用给定的CSS选择器字符串搜索起始元素下的子树。如果找到该元素,则返回其DOM节点。

答案 1 :(得分:1)

您需要这样做才能使if语句生效。

var parentDiv = document.getElementById("parentDiv");
var childDiv = document.getElementById("childDiv");

if (parentDiv.contains(childDiv)) {
  alert("yes");
}
  
<div id="parentDiv">
  <div id="childDiv">
  </div>
</div>