How to loop through dynamically added elements in DOM

event binding on dynamically created elements javascript
how to bind click event in jquery for dynamically added html element
javascript add onclick event dynamically
how to add click event to dynamically added html element in typescript
angular add event listener to dynamically created element
jquery select dynamically added element
click event for dynamically created button jquery
how to add onchange event dynamically in javascript

I have a form which adds/removes elements (via AJAX) depending on what type of item the user wants to submit. It includes div elemets which have the contenteditable="true" attribute enabled so that users can type in to a div.

When submitted the form to the server, I need to loop through all the elements that have the attribute contenteditable="true" and send the data across. I do gathering of data like this:

$('form #Publish, form #Delete').on('click', this, function(e) {
      var FormToSubmit = $(this).parents('form'); // form to submit
      var ButtonClicked = $(this); // which button was clicked publish or delete?
      var serialisedFormArrayObject = [];
      serialisedFormArrayObject.push({
        name: $(this).attr('name'),
        value: $(this).val()
      });

      // loop through contenteditable elements
      var $contentEditableItems = $("[contenteditable=true]"); // this doesn't work on dynamically added elements
      $contentEditableItems.each(function(index) { // add data from elements to form data
        serialisedFormArrayObject.push({
          name: $contentEditableItems[index].id, // ID of div
          value: $contentEditableItems[index].innerHTML // html inside of div
        });
      });
    }

The code above works fine when the page already has the contenteditable div elements on the page. But if they are dynamically brought in, it doesn't seem to catch them in the var $contentEditableItems = $("[contenteditable=true]"); part of the code.

How can I get these elements that exist after the page has loaded?

I add the elements via AJAX which goes to the server and asks it for HTML code. The code returned by the server will be like this:

<div id="Hobbies" contenteditable="true">
 <p>List your hobbies here.</p>
</div>
<div id="Qualifications" contenteditable="true">
 <p>List your qualifications here</p>
</div>

The above gets added to the form dynamically. I don't do any adding/removing of properties/attributes in jQuery.

If you're replacing the elements you bound on, the binding is gone. So replace your binding with:

$(document).on('click', '#Publish, #Delete', function(e) {
  let $clickedElem = $(e.target).closest('#Publish, #Delete'),
      $contentEditableItems = $("[contenteditable=true]");

  console.log($contentEditableItems.length);

})

Now your code will work, even after you replace your form contents (including the #Publish and #Delete buttons).

In conclusion: they container selector (the one you bind on) has to stay in the markup. If you replace it, you lose the binding. $(document) might be too general as container selector (but it's guaranteed to work). Feel free to change it to a more specific one, but make sure it's an element that remains in the page throughout the entire life cycle of your page.

Attaching event handlers to dynamically created JavaScript elements, The problem with dynamically created elements, is that they aren't born with the Taking our knowledge from above, we can loop through our HTML and First I​'m going to setup querySelector, a native DOM selector, in a  Loop through a collection of DOM elements. It is easy to think of a collection of DOM elements as a regular JavaScript array. This is a gotcha that many beginners fall into (including myself). NodeLists don’t share all of the Array’s prototype methods, but there are a heap of ways to achieve the desired result.

first, you need to be sure that the dynamically added content also has contenteditable='true' as you can make it editable only by contenteditable

I think the below code would be more secure to get all the editable contents;

var $contentEditableItems = $("div[contenteditable]").filter(function() {
   return $(this).prop('contenteditable');
});

hope this helps.

How to Bind Click Event to Dynamically Created Elements in jQuery, How to bind click event to dynamically created HTML elements in jQuery If you try to do something with the elements that are dynamically added to DOM using the Let's take a look at an example to understand how it basically works:  In the above jQuery code, “div” as selector is passed and the click event is attached to document itself. So now when dynamic div elements are added to HTML, it’s the responsibility of the document to loop through all matching child elements and then execute the event. You can take a look at the demo here.

Add a common class to all you editable div, like :

<div class="content_editable" contenteditable="true"></div>

Then use class . selector like :

var $contentEditableItems = $('.content_editable');

Loop through Elements, Arrays and Objects using jQuery .each , In this post, I am going to show you how you can loop through DOM elements, For example, I'll create and add class to the <span> elements and pick values  You need event delegation for handling events to dynamically added DOM . Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future. try this: $(document).on

It seems to be case sensitive code. Your dynamicly added code might use a capital where your static code doesn't.

$(document).ready(function(){
  $('#test').append('<div contenteditable="True">test1</div>');
  $('#test').append('<div contenteditable="False">test2</div>');
  $('#test').append('<div contenteditable="True">test3</div>');
  $('#test').append('<div contenteditable="true">test4</div>');
  $('#test').append('<div contenteditable="frue">test5</div>');
});

$('#button').on('click', function(){
  $('[contenteditable="True"]').each(function(){
    console.log($(this).text());
  })
})

$('#button2').on('click', function(){
  $('[contenteditable="true"]').each(function(){
    console.log($(this).text());
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">

</div>
<button id="button">Log True (Capital)</button>
<button id="button2">Log true (No capital)</button>

Binding Click Event to a Dynamically Created Element using jQuery, The .click() method works fine with the <div> element, since the element was present when page was loaded, and it is now DOM ready. Attaching event handlers to dynamically created JavaScript elements. When working with JavaScript, you can sometimes need to create new elements on-the-fly, and from that, you’ll need to do something with that new element. It might be a click, which more often than not will need to execute a function.

Master the art of looping in JavaScript with these incredible tricks, Many times in your code you require to loop through an array of numbers, strings or object. There are just so Looping through DOM elements. Suppose you Next, add the CSS for giving proper design to this html table: Creating New HTML Elements (Nodes) To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

jQuery .on(): Dynamically Added Elements, But the moment a div element is added dynamically (via code), the click which doesn't bind the event to the DOM elements, but it delegates the to loop through all matching child elements and then execute the event. We’ll use querySelectorAll () to grab all elements with demo-class applied to them, and forEach () to loop through them and apply a change. It is also possible to access a specific element with querySelectorAll () the same way you would with an array — by using bracket notation. // Get a NodeList of all .demo elements const demoClasses

Dynamic style - manipulating CSS with JavaScript, If your style elements have id attributes, you can reference them quickly with document. You can also add new style sheets to the page — you can use the document. To remove a style sheet you can use the DOM function parent. To solve this issue, we can use JavaScript to either iterate through all the articles and  This article is an overview of some powerful, fundamental DOM level 1 methods and how to use them from JavaScript. You will learn how to create, access and control, and remove HTML elements dynamically. The DOM methods presented here are not specific to HTML; they also apply to XML. The demonstrations provided here will work fine in any modern

Comments
  • where are you calling this code?
  • It depends on how you call the loop. suppose you add the new elements in the DOM then put this code in a function and call that function.
  • One problem is $('form #Publish').on('click', this, function(e) { isn't valid. Second argument needs to be a selector. What is this?
  • No, this is only the button inside the handler. Should not be adding this as second argument of on()
  • I think the problem is not that the selector does not work, but the function is not run, because the buttons which the function is bound to are probably replaced by ajax content, too. A simple console.log would demonstrate it.
  • @volumeOne, I'll create an example where instead of using $.ajax I'll add the items from a variable. I'm not sure right now, but it might have to do with the fact you're passing this (which I assume to be the window object) as child selector of your click event. Why is it there in the first place?
  • this tells me what button was clicked. I have added a bit more code to make it clearer.
  • That's not how you get the clicked button. You get the button from $(e.target)! this passed as you did, is the outer scope of your binding function, most likely the window object.
  • @AndreiGheorghiu nothing wrong with using this inside handler. Is safer actually than target because target can be a child of this. currentTarget ===this
  • It means you were replacing the button, too. And there went your entire function. That was what was not "working", not the "selector". Nothing would have worked, because the function was not executing after you replaced the buttons.
  • Out of interest, why does jQuery pick up dynamic elements by class name and not by attribute?
  • I think you got down-voted for lack of substance of your answer. It should be crystal clear that adding a class does not change anything. $('[contenteditable]') or $('[contenteditable=true]') are just as valid selectors for the element you posted above. Your answer basically says: "I don't know why your selector does not work.". Considering your reputation and the answer quality one expects from someone like you, as well the fact your answers should guide by example, I'm tempted to down-vote myself, to be totally honest.
  • This assumes OP is using attribute to set new ones. Doesn't explain why OP's code not working. This isn't an answer...just a comment
  • @charlietfl Don't have an example how to code is added. A typing mistake might be the reason since the selector works like a charm. Therefore my answer.