1

I am using javascript to inject a few DOM elements into the page. I am able to inject a single DOM element and apply CSS style to it:

var $e = $('<div id="header"></div>');
$('body').append($e);

$e.css({
    background: '#fbf7f7',
});

Problem: If I have nested elements within $e, how can I apply CSS styles to the parents and its children seperately?

var $e = $('<div id="header"><div class="header-content"><span class="title"></span></div></div>');
3
  • Can't you access elements using their id or class? For example $("#header") or $("#header .header-content") Commented Dec 4, 2012 at 4:58
  • Right, I was thinking using $e instead of selecting through their classes and ids will prevent variable name clashes if the classes and ids already exist on the page its injecting into. If i select by id and classname, there may be clashes Commented Dec 4, 2012 at 5:25
  • Well, if ids already exist that would be a major concern, not just for css. It makes sense for class names. If it's really children you need, then just go with $e.children(). Commented Dec 4, 2012 at 5:36

3 Answers 3

1

As you have applied class to div inside parent element you can simply create a style to that class header-content and apply it.

In order to apply styles dynamically you can simply add class for individual elements like this

$('#id-of-element').addClass("header-content");

you can also find elements inside parent element like the one below

$e.find('.header-content').css('background-color', '#ccc');
Sign up to request clarification or add additional context in comments.

Comments

0

Hi you can add css to any element using .css() method... Try the following example. I have added a div inside $e and applied different style... the thing is to use the id or class of the child inside parent div...

var $e = $('<div id="header"><div id="child"></div></div>');
$('body').append($e);

$e.css({
    background: '#fbf7f7',
});
$('#child').css("background", "red");

Comments

0

To expand on my comments: if you need to access children regardless of any id or class, then just use $e.children().

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.