Search code examples
javascriptjsonselectionsteroids

Why can't I find the id?


I am trying to change the text between the "h3" tags. New text should be moved from json-file. But the programm can not find the "h3"-element while the fields from the json-file are being read correctly. Here is a part of the json-file:

var teachers=JSON.parse( string_teachers );  
var i;
var T_name;
var Subject;
for (i=1; i<teachers.Teachers.length+1; i++) {
  T_name=teachers.Teachers[i-1].T_name;
   Subject=teachers.Teachers[i-1].Subject;
   var str="#"+i;
    $(str).find("h3").text(T_name);
 }

And a part of the html:

 <div class="grid" id="1">

     <img src="teachers/bobr.jpg">
     <h3 >Боброва Даша</h3>
     <p>Математический анализ</p>
</div>
<div class="divider">
<img src="views/divider.png" >
</div>
<div class="grid" id="2">
    <img src="teachers/korolev.jpg">
        <h3>Королев Даня</h3>
        <p>Программирование 1</p>
    </div>

Solution

  • it looks you are missing jQuery function. here:

     (str).find("h3").text(T_name);
    

    Use it:

     $(str).find("h3").text(T_name);
    

    I was missing some at JSON, yor issue is: DOM is no loaded yet when you are trying to access it

    function foo() {
    
    var string_teachers = '{"Teachers":[{"T_name":"value1", "Subject": "value2"},{"T_name":"value2",           "Subject": "value2"}]}'
    
    var teachers = JSON.parse(string_teachers);
    var i;
    var T_name;
    var Subject;
    for (var i = 0; i < teachers.Teachers.length; i++) {
        T_name = teachers.Teachers[i].T_name;
        Subject = teachers.Teachers[i].Subject;
        var str = "#" + (i+1);
        console.log(str)
        $(str).find("h3").html(T_name);
    }
    }
    $(document).ready(foo)