Adding an event listener to an element that does not yet exist in javascript

In jQuery, I can do:

$(document).on("click","a.someBtn",function(e){
    console.log("hi");
});

to add an event listener to an element that does not yet exist. I cannot figure out how to add an event listener to an element that does not exist in vanilla javascript yet.
Obviously, the following does not work:

query.addEventListener( "click", someListener );

Edit

What I would like to do is compare an element using query selectors. I select an item that does not yet exist with querySelectorAll. This is a bit more dynamic than just checking the tag name.

+4
source share
4 answers

target event, . //

document.addEventListener( "click", someListener );

function someListener(event){
    var element = event.target;
    if(element.tagName == 'A' && element.classList.contains("someBtn")){
        console.log("hi");
    }
}
+9

event.target

, .

(function () {
    "use strict";
        document.getElementsByTagName('body')[0].addEventListener('click', function(e) {
        if (e.target.tagName == 'A' && e.target.classList.contains("someBtn")) {
          alert('Clicked');
        }
      }, false);
})();

(function() {
  "use strict";
  var a = document.createElement('a');
  a.textContent = 'Click Me';
  a.href = '#';
  document.body.appendChild(a);

  document.getElementsByTagName('body')[0].addEventListener('click', function(e) {
    if (e.target.tagName == 'A') {
      alert('Clicked');
    }
  }, false);
})();
Hide result
+2

, "" , jQuery .on. :

addLiveListener(scope, selector, event, function reference);

.

/**
 * Adds a istener for specific tags for elements that may not yet
 * exist.
 * @param scope a reference to an element to look for elements in (i.e. document)
 * @param selector the selector in form [tag].[class] (i.e. a.someBtn)
 * @param event and event (i.e. click)
 * @param funct a function reference to execute on an event
 */
function addLiveListener(scope, selector, event, funct) {
  /**
   * Set up interval to check for new items that do not 
   * have listeners yet. This will execute every 1/10 second and
   * apply listeners to 
   */
  setInterval(function() {
    var selectorParts = selector.split('.');
    var tag = selectorParts.shift();
    var className;
    if (selectorParts.length)
      className = selectorParts.shift();

    if (tag != "") {
      tag = tag.toUpperCase();
      var elements = scope.getElementsByTagName(tag);
    } else
      var elements = scope.getElementsByClassName(className);

    for (var i = 0; i < elements.length; i++) {
      if (elements[i][event + '_processed'] === undefined && (tag == "" || elements[i].tagName == tag)) {
        elements[i].addEventListener(event, funct);
      }
    }
  }, 1000);
}

:

/**
 * Adds another anchor with no events attached and lets 
 * our other code auto-attach events
 */
var currentAnchor = 3;

function addAnchor() {
  currentAnchor++;
  var element = document.createElement('a');
  element.href = "#";
  element.innerHTML = "Anchor " + currentAnchor;
  element.className = "someBtn";
  document.getElementById("holder").appendChild(element);
}

/**
 * Adds a istener for specific tags for elements that may not yet
 * exist.
 * @param scope a reference to an element to look for elements in (i.e. document)
 * @param selector the selector in form [tag].[class] (i.e. a.someBtn)
 * @param event and event (i.e. click)
 * @param funct a function reference to execute on an event
 */
function addLiveListener(scope, selector, event, funct) {
  /**
   * Set up interval to check for new items that do not 
   * have listeners yet. This will execute every 1/10 second and
   * apply listeners to 
   */
  setInterval(function() {
    var selectorParts = selector.split('.');
    var tag = selectorParts.shift();
    var className;
    if (selectorParts.length)
      className = selectorParts.shift();

    if (tag != "") {
      tag = tag.toUpperCase();
      var elements = scope.getElementsByTagName(tag);
    } else
      var elements = scope.getElementsByClassName(className);

    for (var i = 0; i < elements.length; i++) {
      if (elements[i][event + '_processed'] === undefined && (tag == "" || elements[i].tagName == tag)) {
        elements[i].addEventListener(event, funct);
      }
    }
  }, 1000);
}

/**
 * Now let add live listener for "a" tags
 */
addLiveListener(document, "a.someBtn", "click", function() {
  alert('Clicked ' + this.innerHTML);
});
a {
  margin-right: 10px;
}
<!-- Add some pre-existing anchors -->
<p id="holder">
  <a href="#" class="someBtn">Anchor 1</a><a href="#" class="someBtn">Anchor 2</a><a href="#" class="someBtn">Anchor 3</a>
</p>

<!-- A button to add dynamic new anchors -->
<input type="button" value="Add anchor" onclick="addAnchor();" />
Hide result
+1

.

$(document).on('click', '#your-target-element', function() { /* Your listener */ });
0

All Articles