[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 244
  • Last Modified:

Import CSS from one ID to another ID using jQuery

Hi all,

I'm wanting to import an existing ID's style ("box") into a different ID's style ("box2"), however my code below does not work as expected.

Does anyone know if this is possible or can direct me to an appropriate jQuery plugin?

Thanks,
Wakie.
<style type="text/css">
	#box { width: 250px; height: 200px; }
</style>

<script type="text/javascript">
$(function() {
	$('box2').css('#box');
});
</script>

Open in new window

0
Wakie
Asked:
Wakie
  • 3
  • 2
1 Solution
 
andrewbleakleyCommented:
That won't work as you have used it. You would have to enumerate each style property and apply the one by one or as a map.

CSS has a more elegant solution though and that is too use classes

<style type="text/css">
        .box { width: 250px; height: 200px; }
</style>

Any element you want to take on the properties just needs to have it's class set as "box", if you are creating boxes dynamically using jquery you can specify a class with $("#element").set("class","box");
0
 
WakieAuthor Commented:
Thanks Andrew,

I ended up using the solution below.

However, any idea why I have to put it at the bottom of the code and not in with the rest of my JavaScript?
<script>
	$("#title").addClass("ui-widget-header ui-corner-all");
	$("#box").addClass("thebox ui-widget-content ui-corner-all");
</script>

Open in new window

0
 
andrewbleakleyCommented:
because you have to wait until the elements have been created by the DOM. That's why most jQuery code is wrapped in document ready code - it ensures that all the elements you are about to reference exist and that there properties are set.

Try

$(document).ready(function() {
   
$("#title").addClass("ui-widget-header ui-corner-all");
$("#box").addClass("thebox ui-widget-content ui-corner-all");

});
0
 
WakieAuthor Commented:
Great stuff, appreciate the help :)
0
 
andrewbleakleyCommented:
Always a pleasure, best of luck with rest of the job
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now