Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery .html() returning undefined despite being defined earlier in the function

i have started using jQuery recently and have bumped into a problem. in a function, i use the .html() method as a substitute to innerHTML (which from what i’ve seen in the documentation, isn’t wrong), but for some reason when i try to check the value i’m setting, it gives me undefined. here’s my code:

let nuevo_producto = $("li").html(() => { return "<input class='marcar-comprado' type='checkbox'/><span class='producto'>" + nombre + "</span><img class='icono-borrar' src='img/delete-icon.png' alt='Borrar'>"});

console.log(nuevo_producto.html())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Right now you are selecting actual DOM element <li>.

If you want to create virtual element, you should pass not selector, but it’s content:

let nombre = 'Product 1';
let nuevo_producto = $("<li>").html(() => { return "<input class='marcar-comprado' type='checkbox'/><span class='producto'>" + nombre + "</span><img class='icono-borrar' src='img/delete-icon.png' alt='Borrar'>"});

console.log(nuevo_producto.html())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading