Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - appending html string to html string in variable

I am trying to create an HTML string and then modify that HTML string with extra HTML and attributes but it's not working. What am I doing wrong?

$(document).ready(function(){
    $('body').on('click', 'button', function(){
        var thing     = '<div class="thing"></div>';
        var close     = '<a href="#" class="close">close</a>';

        $(thing).append(close);

        $('.canvas').append(thing);

        return false;
    });
});

I did get it to work by combining the strings into one variable before appending them to the DOM but this makes what I'm doing harder to read. Is there any other way of doing this?

Here is a fiddle.

like image 696
Travis L Avatar asked Feb 24 '17 15:02

Travis L


People also ask

How do you append text in HTML?

To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.

How append HTML data to div in jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

Can I use innerHTML in jQuery?

jQuery html() MethodThe html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element. When this method is used to set content, it overwrites the content of ALL matched elements.

How do I get just the text from HTML in jQuery?

You could use $('. gettext'). text(); in jQuery.


1 Answers

Updated fiddle.

You have to assign the return of this expression $(thing).append(close); to the variable thing like:

thing = $(thing).append(close);

Else the variable will always hold the default string <div class="thing"></div> as value.

Hope this helps.

$(document).ready(function(){
  $('body').on('click', 'button', function(){
    var thing	  = '<div class="thing"></div>';
    var close	  = '<a href="#" class="close">close</a>';

    $('.canvas').append( $(thing).append(close) );

    return false;
  });
});
.thing {
  width: 50px;
  height: 50px;
  background: red;
}

.close {
  background: blue;
  color: white;
}

.canvas {
  border: 1px solid black;
  width: 500px;
  height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add Thing</button>
<div class="canvas"></div>
like image 100
Zakaria Acharki Avatar answered Sep 18 '22 23:09

Zakaria Acharki