views:

1689

answers:

3

I am appending p tags to a div as I process a json request and would liek to style it according to what is in the request.

$(document).ready(function() {
    function populatePage() {
        var numberOfEntries = 0;
        var total = 0;
        var retrieveVal = "http://www.reddit.com/" + $("#addressBox").val() + ".json";
        $("#redditbox").children().remove();
        $.getJSON(retrieveVal, function (json) {
            $.each(json.data.children, function () {
                title = this.data.title;
                url = this.data.url;
                ups = this.data.ups;
                downs = this.data.downs;
                total += (ups - downs);
                numberOfEntries += 1;
                $("#redditbox").append("<p>" + ups + ":" + downs + " <a href=\"" + url + "\">" + title + "</a><p>");
                $("#redditbox :last-child").css('font-size', ups%20); //This is the line in question
            });
            $("#titlebox h1").append(total/numberOfEntries);
        });
    }

    populatePage()

    $(".button").click(function() {
        populatePage();
    });
});

Unfortunately things are not quite working out as planned. The styling at the line in question is applying to every child of the div, not just the one that happens to be appended at the time, so they all end up the same size, not sized dependent on their numbers.

how can I apply a style to the p tags as they are appended ot the div?

Edit: Thanks Fortes and Veggerby both worked, but i went with Fortes in the end because I did.

+1  A: 

Replace:

$("#redditbox").append("<p>" + ups + ":" + downs + " <a href=\"" + url + "\">" + title + "</a><p>");

with

var p = $("<p>" + ups + ":" + downs + " <a href=\"" + url + "\">" + title + "</a><p>");
$("p", p).css('font-size', ups%20)
$("#redditbox").append(p);

Can probably be condensed even further.

Edit:

Condensed like:

$("#redditbox").append(
   $("<p></p>").css('font-size', ups%20).append(ups + ":" + downs + " <a href=\"" + url + "\">" + title + "</a>")
);
veggerby
A: 

Certain browsers/versions do not support the :last-child CSS selector. In that case they often ignore it and return all elements matching the remainder of the selector. This is possibly what you are seeing.

As usual IE is one such browser.

veggerby's approach should help you get around the need to use :last-child.

Ash
+3  A: 

You can use JQuery's appendTo instead of append. For your example:

$("<p>" + ups + ":" + downs + " <a href=\"" + url + "\">" + title + "</a><p>")
     .css('font-size', ups%20)
     .appendTo('#redditbox');

Here are the docs for appendTo: http://docs.jquery.com/Manipulation/appendTo

Fortes