6

I am new to jQuery. I want to write the following HTML (along with the classes) using jQuery. How can I do this?

<div class="phnbr">
  <div class="phtext">hi how are you, <a target="_blank" href="http://www.xyz.com">click here.</a>
  </div>
</div>
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Ronan
  • 75
  • 1
  • 1
  • 3

3 Answers3

16
$('<div>').addClass('phnbr').append($('<div>').addClass('phtext').append('hi how are you, ').append($('<a>').attr({ target: '_blank', href: 'http://www.xyc.com'}).text('click here.')));
NKCSS
  • 2,716
  • 1
  • 22
  • 38
7
$('<div class="phnbr"> \
  <div class="phtext">hi how are you, <a target="_blank" href="http://www.xyz.com">click here.</a> \
  </div> \
</div>'); // bang done!
Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
  • 5
    Not the best way to represent jQuery imho ;) – NKCSS Apr 08 '11 at 09:21
  • 2
    @NKCSS, This one would be faster that your solution. Moreover, no need of long chained statements. Moreover, shows the power of JQuery to a beginner. etc etc – sv_in Apr 08 '11 at 09:37
  • 1
    I like this answer as it is quite readable how the HTML structure is. Creating objects for each tag and using `append` and `appendTo` is already confusing with 5+ tags in my opinion. – Magnus Bull Mar 27 '19 at 08:30
5

Well you can just use append() or the other DOM Insertion Functions

$(document.body).append('<div class="phnbr"><div class="phtext">hi how are you, <a target="_blank" href="http://www.xyz.com">click here.</a></div></div>');
Khez
  • 10,172
  • 2
  • 31
  • 51