tags:

views:

37

answers:

4

Simple example:

$(document).ready(function(){
 $('body').css({'background-color': '#dddddd', 'font-size': '12pt'});
 $('table tr:odd').addClass('rowShaded');
 $('<p> Oh my learning jQuery is so fun </p>').addClass('myP');
 $('#myButton').click(function() {
  alert($(this).attr("value")); //should display the name of the button
     $('#myTestTable').toggle();
    });


});

$('<p> Oh my learning jQuery is so fun </p>').addClass('myP');

Everything is working fine except that line. Shouldn't it actually show a new paragraph on my page with that text? I dont see it, all it shows is a table in my html and button that I can toggle. I thought you can add HTML elements and jQuery places it in the html file ? My CSS is simple for that element:

.myP{
font-family:verdana;
color:red;
}
+3  A: 

Well, you have to tell jQuery where it should be shown in your page, using e.g. appendTo().

Example:

('<p> Oh my learning jQuery is so fun </p>')
.addClass('myP')
.appendTo('#mydiv');

appends the HTML to the element with ID mydiv (meaning the p element is now the last child of #mydiv).

Felix Kling
I actually ended up using insertAfter() cool thanks, ill accept in 11 minutes
+1  A: 

In that line you created a new HTML element and added a class to it. You then have to add it to the DOM.

$('body').append($('<p> Oh my learning jQuery is so fun </p>').addClass('myP'));
Teja Kantamneni
This also was helpful +1.
A: 
$('***').append('<p> Oh my learning jQuery is so fun </p>').addClass('myP');

replace * with appropriate selecotr

dejavu
This wouldn't work properly. It would not add the class to the new `<p>`, but rather to the container to which it is being appended.
patrick dw
@patrick - very true good comment definately. You want to .addClass to the actual p and not the original selector @dejavu
A: 

As far as I'm aware that's not how jQuery selectors work; you can get all paras with $('p'), or paras with a given id or class... Check out http://www.pamaya.com/jquery-selectors-and-attribute-selectors-reference-and-examples/ for examples of how to reference stuff.

thesunneversets
No, you can generate new HTML this way.
Felix Kling
No downvote but you can certainly add HTML elements right from jQuery.
Oh well, it's good to learn stuff! Time for me to have a play with some jQuery methinks :D
thesunneversets
Yep, I take it all back, jQuery is smart enough to parse $('<p>...</p>') as some new HTML, and not some incomprehensible element to select. Which makes jQuery much smarter than me, apparently!
thesunneversets