1

Someone can help me with the following.

I need to add style to dynamic HTML elements I add with Jquery, but I can not give it to them directly in a stylesheet, since the values of the attributes that I want to change, are different also depending on the element I add.

Simplifying things, I need to styles from Jquery to HTML elements that will add more later.

I appreciate some help.

2 Answers 2

1

If you are adding element dynamically, then at the time of element creation you can add the css on the element like.

$('<p id="createdParagraph"/>')
    .appendTo(document.body)
    .css("color": "white",
        "background-color": "#98bf21",
        "font-family": "Arial",
        "font-size": "20px",
        "padding": "5px");

or

$('p').append('<span class=your_class_name>)

If you want to use lot of properties in different cases then you can create all the possible classes in your stylesheet and you can add/remove those classes using jquery dynamically like -

$("p").addClass('class1');
$("p").removeClass('class1');

Hope this will help you.

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

1 Comment

Hi, thanks for your interest, unfortunately, this method does not help me because the CSS assigns it to the container where you are adding html, while I needed to give it to content that was adding however the code served me, although tube that change a bit the code you had to use it so as explicastes, thanks.
0

You can use jQuery’s css() method to add new CSS properties to an item or change the values of existing properties dynamically using jQuery.

HTML code:

  <p>This is a paragraph.</p>

JQuery code:

  $(document).ready(function(){
    $("p").css({
      "font-size": "20px",
      "text-align": "center",
      "padding": "40px"
    });
  });

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.