0

I have a problem selecting an element from the html throght jQuery. It could be maybe the fact that the element i am trying to access is dynamically insterted throught getJson, but of course before executing the following js. What can be the problem and how can be solved?

<table id="myTable">
<tbody>
    <!-- inserted with getJson -->
    <tr> 
        <td> <input type='checkbox'  id="myInput0"> </td>
        <td class="myClass">some text</td>
    </tr>
    <!-- other rows -->
</tbody>
</table>
var id = "myInput" + 0;

var text = $("#"+id).closest('tr').find('td.myClass').text();   
alert(text)
  • Can you provide complete code sample? – Николай Гольцев Apr 12 '20 at 18:46
  • As you're using an id selector ensure there is only ever 1 element in the DOM which has that id – Rory McCrossan Apr 12 '20 at 18:50
  • @RoryMcCrossan yes every id is unique in my code –  Apr 12 '20 at 18:58
  • @НиколайГольцев my code is very long, i tried to add something that might be useful –  Apr 12 '20 at 19:29
  • I have tried your code and it works, I think your script tag has been placed before your markup (...) in html file. – Николай Гольцев Apr 12 '20 at 19:49
  • @НиколайГольцев no the code script is attached later, but the html element is added with getJson so it is not in the document since the loading –  Apr 12 '20 at 19:52
  • Well :)) You answered your question right now. If getJSON returns promise, so you should place your DOM manipulations after promise would been resolved. If getJSON based on callback, so place DOM manipulations in callback. That's all. Yes, I googled right now, and it's based on callback, so just place your code in passed callback. – Николай Гольцев Apr 12 '20 at 19:56

2 Answers2

0

I tried to recreate the scenario using getJSON and inserting an element dynamically, then you can do something like this:

$( document ).ready(function() {
  const url =  'https://jsonplaceholder.typicode.com/todos/1';
  $.getJSON( url, function( data ) {
    $('#main').append(data.title); 

  });
});

codepen

hope it helps :)

  • Thanks for the help, but it the js code i have already this part. The part of code i posted is placed after this function –  Apr 12 '20 at 19:09
-1

Take a look at this Stack Overflow Q&A - How do I attach events to dynamic HTML elements with jQuery? - there are a few approaches you can take, but the jest of it is that you need to bind to the body or container of your element rather than the element itself.

Welcome to the community user21! Hopefully that info is helpful.

Buck3000
  • 321
  • 4
  • 11
  • Thanks for the help, i read something and it is helpful but still idk why is not working –  Apr 12 '20 at 19:31
  • if i attach a function $(document).on("click", "#somebutton", function(){}) to a button and inside the function i place my code it is working. But can i do it without attaching this function to a button? I just want to be shown as soon as it is loaded –  Apr 12 '20 at 19:48