0

I have this html code,

<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>

And based on that, I want to add an anchor element before #exportShipmentCSV_all.

Here's what I did.

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]);

After doing that,

If the #exportShipmentCSV_all has been clicked, I'd like to check if the element exists using this way

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

which is based on this reference. Is there an "exists" function for jQuery?

But doing so, I got this error in chrome dev tool console.tab

Uncaught TypeError: Cannot read property 'length' of null

Within this code, there are also jquery in it,

Can you suggest the way I should check, if element has been created or not?

Fil
  • 8,225
  • 14
  • 59
  • 85
  • You need to check `null` when using Vanilla JS i.e. `if(document.getElementById('classfilterBtnIsClicked') !== null){//Your code}` – Satpal Nov 27 '18 at 06:12

1 Answers1

0

Document.getElementById() - Return value

An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document.

The returned element object does not have length property, thus you get undefined.

Why use length? You do not need to use length property here, checking the element object itself is enough:

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>
Mamun
  • 66,969
  • 9
  • 47
  • 59