How could an Element get the same css style of another?
I have the following css rule that describes the style of an element with an id named as treeList:
Now I need jQuery to add this rule to another element with, of course, different id such as #fgsf:
Could jQuery able to apply the style rule of #treeList the other id element fgsf?
I don't know much about jQuery, but couldn't this be done with css classes? Is there any reason you need to get the style specifically from another element? You can declare a class in your style tag:
Then you can add it to any element in the HTML as follows:
<div id='fgsf' class='thisClass'>
or in the script if it's a dynamic element:
Apparently jQuery also has addClass and removeClass functions. Hope this helps.
The better option would be to write your css statement as a class instead of as an ID, unless you're having problems with specificity. If it has to be an ID, remember that IDs should be unique, so you should copy your definition and just give it a new id.
As a good html rule, always try and code in the lowest specificity possible to achieve the effect you want, it will help keep your html maintainable.
I needed this question because of I have a hierarchal menu list script maintained by jQuery for hide and display menu's elements in a PHP script. However, in some pages of the script, I have to deal with two menus. The menu skeleton is included in div with id = treeList, so selecting elements with the same id value should halt jQuery selecting, so I needed to dynamically change the id value with some suffix and then by some way set its css to be equaled to the #treeList set in the CSS file.
However, I followed the approach of adding class attribute to the the div id #treeList and instead of selecting the div with the id alone I selected it using both id and class name, while class name is dynamically generated by the PHP as follows:
<?php $suffix = rand(1,1000); ?>
$('#treeList.<?php echo 'c'.$suffix;?>');
<div id="treeList" class="<?php echo 'c'.$suffix;?>">
so generate a tag param to handle the switching, and apply the CSS via a class.
as a side note, I personally wouldn't use 'id' for this, instead add a 'data-' tag (so it stays html5 compliant). while either will technically work, I try to separate layout from interaction.
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread