0

I have a page that gets a div using jquery's post method. I then try to apply css to the divs and it doesn't work. when i use jquery to apply css on divs that are already on the page, it works for them.

Jquery:

$('#next').click(function() {

    $.post('getquestions.php', {number: number}, function(result){

        $('#questionArea').html(result);
    });

$('.quest').css( "border", "13px solid red" );  //this doesn't work

});

Echoed out from getquestions.php (this is working correctly):

    echo "<div id='question" . $question_number . "' class='quest'>";
6
  • use $('#questionArea').find('.quest').css( "border", "13px solid red" ); Commented Mar 30, 2015 at 2:59
  • just tried it. didnt work :( Commented Mar 30, 2015 at 3:01
  • 1
    this seems to be already an issue that was answered. Did you try moving the CSS definitions to the css file as suggested in stackoverflow.com/questions/16751124/… Commented Mar 30, 2015 at 3:02
  • @Bala what do you mean by move it to the css file? i checked that link but i still dont understand Commented Apr 2, 2015 at 22:25
  • i meant to move the style definitions to a CSS file instead of placing it in the html file in a <style> tag. once in a CSS file add it to the page via <link> tag. Hope that helps. Commented Apr 3, 2015 at 2:32

3 Answers 3

1

it's because your div with class quest is not available when you execute the jquery's css function. Since $.post is an async function, the div is only added to the DOM by $('#questionArea').html(result); when $.post's callback is executed, so you should do the css call there.

should be like this:

$('#next').click(function() {

    $.post('getquestions.php', {number: number}, function(result){

        $('#questionArea').html(result);
        // the div is just added
        $('.quest').css( "border", "13px solid red" );
    });
    // the div is not added to DOM yet since $.post has not finished fetching the result

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

Comments

0

Try with $(document).find('.quest')

Comments

0

How about trying to add the css in .done() after post request? Like

$.post( "example.php", function() {

    alert( "success" );

})

.done(function() {

    alert( "second success" );

});

Or

var posting = $.post( url, { s: term } );

// Put the results in a div

posting.done(function( data ) {

var content = $( data ).find( "#content" );

$( "#result" ).empty().append( content );

});

Source : jQuery.post

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.