-2

I am adding div element after a button is clicked, but only if it doesn't already exist (from a previous click).

Currently it keeps adding the element as the new DOM doesn't seem to be picked up by JQuery.

   var validationMessage = function(msg, elemId) {
      var valId = elemId + "_valId";
      if($(valId).length == 0) {
          $("<div id='" + valId + "' class='error-message'>" + msg + "</div>").insertAfter(elemId);
      }
    };

I run validationMessage in my click event:

$("#ele1").click(function(e) {
   // validationMessage called in here
});

Why doesn't jQuery pickup the new DOM?

I'm using 1.9.1

Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • 2
    Possible duplicate of [Click event doesn't work on dynamically generated elements](http://stackoverflow.com/questions/6658752/click-event-doesnt-work-on-dynamically-generated-elements) – Tyler Roper Mar 15 '17 at 21:31
  • Shouldn't it be `if ($("#"+valId).length == 0) {` ? – bcr666 Mar 15 '17 at 21:33
  • @Brianbcr666Ray not in my case, elemId includes the # already (I will rename elemId to elemSelector) – Blankman Mar 15 '17 at 21:35
  • Your question is kinda confusing. Here's a Stack answer for creating divs in jquery http://stackoverflow.com/questions/867916/creating-a-div-element-in-jquery – Mark Bellamy Mar 15 '17 at 21:35
  • @Blankman then don't you need to strip the "#" off of valId in `$("
    " + msg + "
    ").insertAfter(elemId);` ?
    – bcr666 Mar 15 '17 at 21:36
  • Here is a great Stack answer which i think directly addresses your problem. http://stackoverflow.com/questions/3373763/jquery-how-to-find-if-div-with-specific-id-exists – Mark Bellamy Mar 15 '17 at 21:40

1 Answers1

0

function genText(text){
if(jQuery){
var ef = document.createElement("div");
ef.innerHTML = text;
ef.setAttribute('id', 'msg');
ef.setAttribute('title', 'this is a title');
if(!document.getElementById('msg')){
$(ef).appendTo("body");
}else{
console.warn("Element already exists.");
}
}else{
console.warn("jQuery hasn't loaded in, yet.");
}
}
<style type="text/css">#msg{width: 200px; height:75px; background: white; border: 1px solid #000; color: black; cursor: text; box-shadow: 2px 2px 4px rgb(0,0,0);}</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="genText('Hi')">Generate Text</button>

You can do this by doing an if statement for your ID as shown above. Fortunately, this is quite simple after creating your element, and is probably even easier to do without jQuery unless you're a little more knowledgeable of the abilities of jQuery. This is a really simple example, and since I'm guessing you're going to be using jQuery, I added in the if jQuery. One last thing, to prevent errors when jQuery is not loaded, wrap everything around a try catch statement so errors don't stop the script.