load html element with id

2

I have to change a list html from javascript . my code is

document.getElementById("my_element").innerHTML = "<li id="my_li">...</li>";

Apparently it works correctly and the block loads perfectly, but without the id.

document.getElementById("my_li") // devuelve NULL

What's happening?

edition: that's my code, the problem continues

document.getElementById("my_element").innerHTML = '<li id="my_li">...</li>';
    
asked by nicolas 10.04.2017 в 01:06
source

1 answer

2

You can not use double quotes in the chain that you are enclosing with them, I explain, the correct thing would be:

document.getElementById("my_element").innerHTML = '<li id="my_li">.../li>';

or

document.getElementById("my_element").innerHTML = "<li id=\"my_li\">.../li>";

Any of the 2 examples will work for you.

Under the fact that you do not leave much code to check where you are making the mistake, I can only give you some examples of how to do it.

Here is an example made with jQuery:

$(document).ready(function () {
 $("button").on("click",function () {
  $("ul").html('\
   <li id="My_li_a">lista a</li>\
   <li id="My_li_b">lista b</li>\
   <li id="My_li_c">lista c</li>\
  ');
  setTimeout('alert($("#My_li_a").text());',100);
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="My_Element">
 <li>lista 1</li>
 <li>lista 2</li>
 <li>lista 3</li>
</ul><br>
<button>cambar lista</button>

or if you prefer javascript:

function changeList() {
 document.getElementById("My_Element").innerHTML='\
   <li id="My_li_a">lista a</li>\
   <li id="My_li_b">lista b</li>\
   <li id="My_li_c">lista c</li>\
  ';
  setTimeout('alert(document.getElementById("My_li_a").innerHTML);',100);
};
<ul id="My_Element">
 <li>lista 1</li>
 <li>lista 2</li>
 <li>lista 3</li>
</ul><br>
<button onClick="changeList()">cambar lista</button>

Compare this code with yours and you will find the error, Regards ..;))

    
answered by 10.04.2017 в 01:19