Can I change style of some div link. Here is what I mean
<div id="somediv">something/div>
Lets say I have css like this :
#somediv a{
color:#000;
}
Now for instance upon some action such as mouse click on any element I want to change somediv a link css to
#somediv a{
color:#00ffff;
}
I know how to select div, by using Document.get.elementById('somediv') Is it possible to select a by using above method or any other?
Thank you
DETAILS: Yes I know how to select it using jquery, or prototype .. I can't use any of those..
If you just want to apply a style to a particular element, it's very easy to do:
document.getElementById('whatever').style.color = '#f0f';
If you actually want to apply cascading styles (eg: #someDiv a), then it's not so easy (though it is definitely possible). I would suggest applying a new class to something, and having a pre-existing rule in your CSS.
CSS:
#someDiv a {
color: #000;
}
#someDiv.awesome a {
color: #f0f;
}
Javascript:
document.getElementById('someDiv').className = "awesome";
Yep, you can modify the actual CSS rules at runtime. See Totally Pwn CSS with Javascript for more details.
If you're using jQuery or YUI, there's some good info in question 1079237
document.getElementById ( 'somediv' ).children[0].style.color = 'new color';
assuming the A tag will be the first element inside your DIV
You could use CSS behaviors for this:
For instance:
#somediv a:hover
{
color:#0ff;
}
Otherwise, you may create a dedicated class (used when an element is click for example):
#onclickclass
{
color:#0ff;
}
Then in JavaScript, on onClick event, do:
document.getElementById('somediv').className = 'onclickclass';
And to change the style use
document.getElementById('somediv').className = 'your-css-class';
If you really want to select the anchor you would have to then traverse the document.getElementById('somediv').children array.
As others have suggested though the simpler answer would be to set the className attribute on your div and let the CSS style cascade onto the anchor tag.
Related
I had a problem that a new dynamic div is added with the dynamic class name while the page is refreshed every time.
For example
<div class="ABGeGGCcJeBCDEGD" data-app-name="">
Here the class=" ABGeGGCcJeBCDEGD", when I reload the page the class name is changed automatically.
So, I need to remove or hide that div.
Note
The div is not present in the code side, but it is created dynamically.
Thanks in advance
You should find another way to identify div instead of class name, e.g. DOM tree.
Also you can try to make "white list" of visible divs. Something like
Make ALL divs hidden
Get white list and show divs with these classes.
You can use event on id
Example is here.
$('#testDiv'). remove()
Let me know if this case is not going to work
You have 3 options, as far as I can see.
1. Does the class always start or end the same way?
If so, you can target that in CSS.
div[class^="ABGe"] { display: none; }
div[class$="DEGD"] { display: none; }
2. Does the element have any other classes or attributes that you can target.
If so, you can target them in CSS instead.
div[data-app-name] { display: none; }
3. Can you modify the markup?
If so, you can wrap the element in something that won't change.
<div class="hide-contents">
<div class="ABGeGGCcJeBCDEGD" data-app-name="">
</div>
You can then target that in CSS.
.hide-contents > div { display: none; }
I hope one of those options is useful.
I need to define a div's background color on :hover with jQuery, but the following doesn't seem to work:
$(".myclass:hover div").css("background-color","red");
How can I get the same result? It's important that it has to be done with jQuery but for some reason it doesn't work. Any suggestions? Thanks!
I would suggest to use CSS over jquery ( if possible) otherwise you can use something like this
$("div.myclass").hover(function() {
$(this).css("background-color","red")
});
You can change your selector as per your need.
As commented by #A.Wolff, If you want to use this hover effect to multiple classes, you can use it like this
$(".myclass, .myclass2").hover(function(e) {
$(this).css("background-color",e.type === "mouseenter"?"red":"transparent")
})
Js Fiddle Demo
You can try this:
$(".myclass").mouseover(function() {
$(this).find(" > div").css("background-color","red");
}).mouseout(function() {
$(this).find(" > div").css("background-color","transparent");
});
DEMO
I know this has an accepted answer but if anyone comes upon this, my solution may help.
I found this question because I have a use-case where I wanted to turn off the :hover state for elements individually. Since there is no way to do this in the DOM, another good way to do it is to define a class in CSS that overrides the hover state.
For instance, the css:
.nohover:hover {
color: black !important;
}
Then with jQuery:
$("#elm").addClass("nohover");
With this method, you can override as many DOM elements as you would like without binding tons of onHover events.
Well, you can't add styling using pseudo selectors like :hover, :after, :nth-child, or anything like that using jQuery.
If you want to add a CSS rule like that you have to create a <style> element and add that :hover rule to it just like you would in CSS. Then you would have to add that <style> element to the page.
Using the .hover function seems to be more appropriate if you can't just add the css to a stylesheet, but if you insist you can do:
$('head').append('<style>.myclass:hover div {background-color : red;}</style>')
If you want to read more on adding CSS with javascript you can check out
one of David Walsh's Blog posts.
Use JQuery Hover to add/remove class or style on Hover:
$( "mah div" ).hover(
function() {
$( this ).css("background-color","red");
}, function() {
$( this ).css("background-color",""); //to remove property set it to ''
}
);
It's too late, however the best example, how to add pseudo element in jQuery style
$(document).ready(function(){
$("a.dummy").css({"background":"#003d79","color":"#fff","padding": "5px 10px","border-radius": "3px","text-decoration":"none"});
$("a.dummy").hover(function() {
$(this).css("background-color","#0670c9")
}).mouseout(function(){
$(this).css({"background-color":"#003d79",});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<a class="dummy" href="javascript:void()">Just Link</a>
I have some basic css:
#awesome1{
color: red;
}
and html:
<div id="awesome1"></div>
I want to change the id awesome1 to awesome2 with jQuery, but keep the css from old id.
But when I type:
jQuery('#awesome1').attr('id', 'awesome2');
It changes the div's id in DOM, but of course, my div loses the color: red.
Is there a way to change the "id in css" or "copy all the attributes" (I cannot assume that's only color) from old id to new one?
Update, clarification:
The point is, I change the id to another dynamically, based on some ajax data - I don't know (at the time I generate the css), which id it will be, so I cannot assume that it will be awesome2 and hard-code it in e.g. css.
P.s.
Please read especially the bold text before posting new answers. I'm aware of methods when I could assume what would be the new id and hard-code it to css, or resign from id for classes. But in my example, I cannot. And my problem is like the topic: Change id but keep the css related to the old id in jQuery.
What about you add the following in your CSS ?
#awesome2{
color: red;
}
Or instead of using CSS on ID use it on class like this
<div id="awesome1" class="something"></div>
.something{
color: red;
}
This way you will always keep the same style from the class but can use whatever ID you want
This plugin will allow you to copy css from one element to another
https://github.com/moagrius/copycss
Also similar question was already answered on StackOverflow here -> Can jQuery get all CSS styles associated with an element?
jQuery('#awesome1').attr('id', 'awesome2');
$('#awesome2').css('color', 'red');
If all your id tags are going to start with the word 'awesome', you could change your CSS to:
[id^=awesome]{
color: red;
}
Demo Fiddle
If they just contain the word awesome, chante the caret (^) to an asterisk.
That said, I'd recommend you take a step back and think if there isnt a better way to do what you intend.
<html>
<head>
<title>test</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
<style type="text/css">
div[id^=awesome] {
color: red;
}
</style>
<script type="text/javascript">
var something = function () {
jQuery('#awesome1').attr('id', 'awesome2');
}
</script>
</head>
<body>
<div id="awesome1">this is test</div>
</body>
</html>
There are only two times you should be associating CSS with an ID:
When the element with that ID is going to keep that ID throughout the page's lifetime.
When it's OK for the element to lose those properties if it loses the ID.
When you don't want things to change even though an element's ID changes, you need to use a different selector for those things. I recommend using a class, something like this CSS:
.awesome {
color: red;
/* other stuff that shouldn't change when the ID changes */
}
#awesome1 {
/* ID-specific CSS for #awesome1 */
}
#awesome2 {
/* ID-specific CSS for #awesome2 */
}
and this HTML:
<div id="awesome1" class="awesome"></div>
Now, when you change the ID, the element will keep the things from its .awesome class, but change according to its ID for things that should change for that.
How do I set the visited color of an "a" tag. here is the code I have
theobj.find('a:visited').css('color', thejson.WidgetInfo.TextColor);
The above code is not working. I can only use inline css. Is there a way to do this?
You could construct a style tag, and then write it to the page.
var visited_link_styling = "<style> a:visited{ color:'red'; } </style>";
$('head').append( visited_link_styling );
This might get a little frustrating because JavaScript isn't good at multiline strings.
There isn't a visited selector in jQuery that I am aware, but a similar question points to a plugin to handle this Remy Sharp Visited Plugin
I would suggest you to have a css class and set that class instead but since you can only use inline style you can try this
theobj.find('a').attr("style", "color:#000000 !important");
You can't actually set any properties on an element that only apply to some pseudoselector like visited. CSS documents are declarative, in that you include the CSS in your document and then the set of rules becomes available. JavaScript is not declarative, but executed, which means you can only catch some event and then respond to that. In other words; you can select all the links that are visited and set the color for each, but you can't set the color for visited links.
Now, in order to achieve what you want, you can set a 'live' event handler for the click event on each anchor and then apply the CSS accordingly.
Out of curiosity; why don't you just set the rule in a style element or in a css document?
Is there a reason you are wanting to use jQuery and not pure CSS? Should visited links behave differently than unvisited links?
Depending on your answers to the above questions, the solutions will vary.
CSS:
a:hover { color: #000; }
jQuery (for multiple link color attributes):
var ele = $("#widget a"); // Replace the desired element/object here
var eleColor = ele.css('color'); // Grab what the element's color is
if(eleColor != '#000000' || eleColor != '#000'){ // If it doesn't match X or Y
ele.css("color","000"); // Set to default color
}
^Substituting desired colors above.
Or approach 2:
$("#widget a").css("color","000"); // Set all links to #000
Or approach 3:
$("#widget a").click(function(){ $(this).css("color","000"); });
Working example: http://jsfiddle.net/9N5Xe/
How can I select all elements that have a specific CSS property applied, using jQuery? For example:
.Title
{
color:red;
rounded:true;
}
.Caption
{
color:black;
rounded:true;
}
How to select by property named "rounded"?
CSS class name is very flexible.
$(".Title").corner();
$(".Caption").corner();
How to replace this two operation to one operation. Maybe something like this:
$(".*->rounded").corner();
Is there any better way to do this?
This is a two year old thread, but it was still useful to me so it could be useful to others, perhaps. Here's what I ended up doing:
var x = $('.myselector').filter(function () {
return this.style.some_prop == 'whatever'
});
not as succinct as I would like, but I have never needed something like this except now, and it's not very efficient for general use anyway, as I see it.
Thank you, Bijou. I used your solution, but used the jQuery .css instead of pure javascript, like this:
var x = $('*').filter(function() {
return $(this).css('font-family').toLowerCase().indexOf('futura') > -1
})
This example would select all elements where the font-family attribute value contains "Futura".
You cannot (using a CSS selector) select elements based on the CSS properties that have been applied to them.
If you want to do this manually, you could select every element in the document, loop over them, and check the computed value of the property you are interested in (this would probably only work with real CSS properties though, not made up ones such as rounded). It would also would be slow.
Update in response to edits — group selectors:
$(".Title, .Caption").corner();
Similar as Bijou's. Just a little bit enhancement:
$('[class]').filter(function() {
return $(this).css('your css property') == 'the expected value';
}
).corner();
I think using $('[class]') is better:
no need to hard code the selector(s)
won't check all HTML elements one by one.
Here is an example.
Here is a clean, easy to understand solution:
// find elements with jQuery with a specific CSS, then execute an action
$('.dom-class').each(function(index, el) {
if ($(this).css('property') == 'value') {
$(this).doThingsHere();
}
});
This solution is different because it does not use corner, filter or return. It is intentionally made for a wider audience of users.
Things to replace:
Replace ".dom-class" with your selector.
Replace CSS property and value with what you are looking for.
Replace "doThingsHere()" with what you want to execute on that
found element.
Good luck!
Custom CSS properties aren't inherited, so must be applied directly to each element (even if you use js to dynamically add properties, you should do it by adding a class), so...
CSS
.Title
{
color:red;
}
.Caption
{
color:black;
}
HTML
You don't need to define a rounded:true property at all. Just use the presence of the 'Rounded' class:
<div class='Title Rounded'><h1>Title</h1></div>
<div class='Caption Rounded'>Caption</div>
JS
jQuery( '.Rounded' ).corner();