0

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?

2
  • Try jQuery.parseHTML() instead of $. Commented May 23, 2016 at 15:20
  • Instead of selecting the id and then using find with the selected element just pass the id directly to the find: jsfiddle.net/b3Lqj3ka Commented May 23, 2016 at 15:22

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.