Reputation: 195
Problem: I can't modify an HTML element I created inside a function.
Code:
I read I can create an element from a string this way.
var base_html = $("<div id='base'><div id='chart_container_bars'></div>"+
"<br>"+
"<br>"+
"<div id='chart_container_lines'></div>"+
"<table class='table table-bordered' id='tabla_servicios' style='width:100%; padding:12px'>"+
"</table>"+
"</div>");
So I assumed I could use selectors to modify that piece of HTML code like this.
var tabla_servicios = base_html.find($("#tabla_servicios"));
tabla_servicios.html("<p>HI</p>");
And then get the HTML back to a string with:
var html_str = base_html.html();
But I haven't been able to do it.
Desired result:
var final_html_str = $("<div id='base'><div id='chart_container_bars'></div>"+
"<br>"+
"<br>"+
"<div id='chart_container_lines'></div>"+
"<table class='table table-bordered' id='tabla_servicios' style='width:100%; padding:12px'>"+
"<p>HI</p>"+
"</table>"+
"</div>");
Question:
Is there a way to create an HTML element from a string and modify it with selectors afterwards?
Upvotes: 0
Views: 50
Reputation: 3683
In jquery find function you have to pass the selector as a string.
var base_html = $("<div id='base'><div id='chart_container_bars'></div>"+
"<br>"+
"<br>"+
"<div id='chart_container_lines'></div>"+
"<table id='tabla_servicios' class='table table-bordered' id='tabla_servicios' style='width:100%; padding:12px'>"+
"</table>"+
"</div>");
var tabla_servicios = base_html.find("#tabla_servicios");
tabla_servicios.html("<p>HI</p>");
var html_str = base_html.html();
console.log(html_str);
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
Upvotes: 3