代码之家  ›  专栏  ›  技术社区  ›  Fil

检查元素是否在javascript中创建[重复]

  •  0
  • Fil  · 技术社区  · 6 年前

    我有这个html代码,

    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="shipment-filter">
        <a class="dropdown-item" href="javascript:void(0)" data-table="ShipmentsDataTable" id="exportShipmentCSV_all"> CSV - All Shipments </a>
    </div>
    

    基于此,我想在 #exportShipmentCSV_all .

    我就是这么做的。

    let newElementA = document.createElement('a');
    newElementA.setAttribute('id', 'classfilterBtnIsClicked');
    newElementA.dataset.classfilterBtnIsClicked = true;
    
    let currentDiv  = document.getElementById('shipment-filter');
    currentDiv.insertBefore(newElementA, currentDiv.childNodes[0]);
    

    如果 #全部导出 已经单击,我想用这种方式检查元素是否存在

    if (document.getElementById('classfilterBtnIsClicked').length) {
        // Code here
    }
    

    基于这个参考。 Is there an "exists" function for jQuery?

    Uncaught TypeError:无法读取null的属性“length”

    在这段代码中,还有jquery,

    2 回复  |  直到 6 年前
        1
  •  0
  •   Yousaf    6 年前

    你可以检查一下 document.getElementById('classfilterBtnIsClicked') 回报 null 或者不。如果元素不存在, 会回来的 无效的

        2
  •  0
  •   Mamun    6 年前

    Document.getElementById() - Return value

    描述与指定ID匹配的DOM元素对象的元素对象,如果在文档中找不到匹配的元素,则为空。

    返回的元素对象没有 长度 财产,所以你得到 未定义 .

    为什么使用 ? 你不需要使用 长度 属性,检查元素对象本身就足够了:

    let newElementA = document.createElement('a');
    newElementA.setAttribute('id', 'classfilterBtnIsClicked');
    newElementA.dataset.classfilterBtnIsClicked = true;
    
    let currentDiv  = document.getElementById('shipment-filter');
    currentDiv.insertBefore(newElementA, currentDiv.childNodes[0]);
    
    if (document.getElementById('classfilterBtnIsClicked')) {
        console.log('Element exists');
    }
    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="shipment-filter">
        <a class="dropdown-item" href="javascript:void(0)" data-table="ShipmentsDataTable" id="exportShipmentCSV_all"> CSV - All Shipments </a>
    </div>