Select all elements that have a specific CSS, using jQuery - javascript

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();

Related

Target/style an element’s attributes with JavaScript

I'm attempting to change the style of the div element below using JavaScript, but by using its attribute as the selector instead of the class:
<div class="radio-wrapper" data-option-method="Option-A">
For example, I'm able to achieve the desired effect with the following CSS:
.radio-wrapper[data-option-method="Option-A"] { display: none; }
But I'm not having any luck when I attempt the same in the JS:
document.getElementsByClassName(".radio-wrapper[data-option-method="Option-A"]").style.display = "none";
I'm sure this is a fairly simple one, but I'm struggling to research a clear answer, greatly appreciate any suggestions!
First of all, you have a clear syntax error. Your browser console is undoubtedly pointing this out to you. Always check the console for errors.
Since your string contains double-quotes, use single-quotes for the string itself:
'.radio-wrapper[data-option-method="Option-A"]'
Aside from that, document.getElementsByClassName is the wrong function to use here. What you have isn't a class name, it's a more complex selector. document.querySelector can find the element based on that:
document.querySelector('.radio-wrapper[data-option-method="Option-A"]').style.display = "none";
Alternatively, if there are multiple matching elements and you want to target all of them, use querySelectorAll and iterate over the results:
let elements = document.querySelectorAll('.radio-wrapper[data-option-method="Option-A"]');
for (let el of elements) {
el.style.display = "none";
}
The problem is that isn't the class name. ([data-option-method="Option-A"] is an attribute)
Try it with:
document.querySelector('.radio-wrapper[data-option-method="Option-A"]')
If you want to select multiple, use querySelectorAll but bare in mind that returns an array.
Also watch out for the `, ", and ' in strings, either escape them with a " or combine them as I did.

select html object without id

Edit: one missing piece of information - I can't use the class selector because there are more divs with the same class. I already thought of that, but I forgot to mention it. I have no idea why my post got downvoted, but it seems awfully silly considering I provided a lot of information, gave it honest effort, and tried to be verbose with code examples. People on this forum are ridiculous sometimes.
I'm trying to set the id of a div that doesn't have one and there's no way I can give it one upon generation of the page. I've tried using jquery (.each, .contains, .find, .filter, etc.) and I can't seem to get it right. I know a ton of people have asked this question, but none of the answers made sense to me.
I have the ability to set the text (html?) of the div, but nothing else. It ends up looking like this:
<div class="dhxform_note" style="width: 300px;">Remaining letters: 500</div>
I want a handle to the div object so I can show the user how many more letters they can type by updating the text.
Using this:
$("div")
returns a list of all divs on the page. I can see the target div in the list, but I can't get jquery to return a single object.
I know it can also be done with something like this:
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++) {
if( /^Remaining letters/.test(divs[i].innerText) )
divs[i].id = "kudosMsgNote"
}
}
but I was hoping to complete this with a cleaner looking solution involving jquery. I also simply want to know how to do it with jquery, aesthetics not withstanding.
Use a class selector.
var theDivViaTheClass = $(".dhxform_note");
Class Selector (“.class”)
Description: Selects all elements with the given class.
version added: 1.0
jQuery( ".class" )
class: A class to search for. An
element can have multiple classes; only one of them must match.
For class selectors, jQuery uses JavaScript's native
getElementsByClassName() function if the browser supports it.
You seem to be targeting the <div> by its text. Try using the :contains selector:
$("div").filter(':contains("Remaining letters")').first().attr("id", "kudosMsgNote");
The .first() is to make sure you don't set the same id for multiple elements, in case multiple elements contain the text "Remaining letters".
Here's the docs for the :contains selector: http://api.jquery.com/contains-selector/
Be careful, the text you're looking for is case sensitive when using :contains!
Is that div the only one with the class dhxform_note? If so, you can use the class selector:
$('.dhxform_note').html();
With jQuery, you can specify any css selector to get at the div:
$(".dhxform_note").attr("id", "kudosMsgNote");
will get you this element as well.
Selecting on inner text can be a bit dicey, so I might recommend that if you have control over the rendering of that HTML element, you instead render it like this:
<div name="remainingLetters" class="dhxform_note" style="width: 300px">Remaining Letters: 500</div>
And get it like this:
$("[name=remainingLetters]").attr("id", "kudosMsgNote");
However, it's possible that you really need to select this based on the inner text. In that case, you'll need to do the following:
$("div").each(function() {
if ( /^Remaining letters/.test($(this).html()) ) {
$(this).attr("id", "kudosMsgNote");
}
});
If you cannot set id for whatever reason, I will assume you cannot set class either. Maybe you also don't have the exclusive list of classes there could be. If all those assumptions really apply, then you can consider down your path, otherwise please use class selector.
With that said:
$("div").filter(function() {
return /^Remaining letters/.test($(this).text())
}).attr('id', 'id of your choice');
For situations where there are multiple divs with the class dhxform_note and where you do not know the exact location of said div:
$("div.dhxform_note").each(function(){
var text = $(this).text();
if(/^Remaining letters/.test(text)){
$(this).attr("id", "kudosMsgNote");
}
});
EXAMPLE
If, however, you know that the div will always be the 2nd occurrence of dhxform_note then you can do the following:
$("div.dhxform_note").get(1).id = "kudosMsgNote";
EXAMPLE
Or do a contains search:
$("div.dhxform_note:contains('Remaining letters')").first().attr("id", "kudosMsgNote");
EXAMPLE

Javascript/jQuery .each and syntax issue

I'm having some trouble writing a function to change a background image on a div on document.ready
I haven't made a jsfiddle as i think the problem is just my poor (but improving) jQuery skills. Please let me know if you think one is needed.
Background Info ->
I have a collection of div's with a class of portlet-visible or portlet-hidden, each of these div's will have another class of red-arrow (or a different color, but once i have one color it should be easy to extrapolate). When the page loads i would like a function that can find all divs with a class of portlet-hidden or portlet-visible and see if those have a class of red-arrow. If they do then change the background image src to a different value.
Im really struggling to work this one out, and any help is much appreciated.
My HTML
<div class="portlet-visible red-arrow"></div>
My CSS
div.portlet-visible
{
position:absolute;
top:12px;
right:10px;
background-image:url(../images/red-arrow-up.png);
width:14px;
height:14px;
}
And finally my javascript
$(document).ready(function() {
$(".portlet-hidden" && ".portlet-visible").each(function() {
if ($("this").hasClass(".red-arrow")) {
$(this).css(background-image, url('"url(../images/blue-arrow-up.png)"')
};
});
});
Multiple selectors should be separated by a comma(,) and also css method takes a string or a map. Try this.
$(document).ready(function() {
$(".portlet-hidden, .portlet-visible").each(function() {
if ($(this).hasClass("red-arrow")) {
$(this).css('background-image', "url('../images/blue-arrow-up.png')")
};
});
});
I would have written the selector this way
$(".portlet-hidden, .portlet-visible")
Unless there's a specific reason you want to do this with jQuery you should just use CSS...
div.portlet-visible
{
background-image:url(../images/red-arrow-up.png);
width:14px;
height:14px;
}
div.portlet-visible.red-arrow
{
background-image:url(../images/blue-arrow-up.png);
}
Any div with the class "portlet-visible" is defined in the first block, and any div with the classes "portlet-visible" and "red-arrow" will use the same css, but also apply the new background image.
http://jsfiddle.net/johncmolyneux/gcm5b/
First... Archer's answer is spot on-- what you're trying to do with jQuery can be done with CSS alone.
But if for some reason you do need jQuery, a few things are wrong here.
First, as justtkt said in his answer, your selector is wrong. There is no need (and is syntactically wrong) to use conditional operators like && or || in a jQuery selector. This is simply because there is already conditional syntax built in to CSS, upon which jQuery selectors are directly based.
.this-class.that-class
Selects all elements with both .this-class, and .that-class.
#this-id.that-class
Is a very (possibly overly) specific declaration that select an element (there should only be one ID per page) with both #this-id and .that-class
For more on selectors, please read this very thorough, complete, and educational link http://www.w3.org/TR/selectors/
Additionally and importantly
This line:
$("this").hasClass(".red-arrow")
Is wrong! hasClass does not require a selector (the ".") because it only takes a class. It should be
$("this").hasClass("red-arrow")
Also!!
$(this).css(background-image, url('"url(../images/blue-arrow-up.png)"')
This line has some errors... should be:
$(this).css("background-image", "url(../images/blue-arrow-up.png)")
although I think the following syntax is easier:
css({'background-image' : 'url(../images/blue-arrow-up.png)'})
Your selector is just incorrect. If you want to match things with both classes, it'd be:
$('.portlet-hidden.portlet-visible').each( ...
If you want to match either of the classes:
$('.portlet-hidden, .portlet-visible').each( ...
The expression ".portlet-hidden" && ".portlet-visible" will always evaluate to just ".portlet-visible".
Instead of && two selectors together, use the multiple selector like $(".portlet-hidden, .portlet-visible") or the .add() method to build up your jQuery.
Your current line is actually anding the two strings together, which I believe will return boolean true in Javascript.
if ('$("this").hasClass(".red-arrow")') { <--- this condition is a string here
Should be:
if ($(this).hasClass(".red-arrow")) {
change in selector ".portlet-hidden,.portlet-visible"
change if condition to boolean from string
change in css.
$(".portlet-hidden,.portlet-visible").each(function(){
if ($("this").hasClass("red-arrow")){
$(this).css("background-image", "url('../images/blue-arrow-up.png')");
}
});

A quick way of hiding divs?

I have the following line of code
document.getElementById("divName").style.display = "none";
How do I hide a bunch of layers at once with totally different names without writing the line of code that often?
Thanks
Felix's thoughts are good. There's a third way: Since they all share a common ancestor (body), you can hide them by adding a class to body and having rules in the CSS that match the actual elements in question, like so:
body.foo table {
display: none;
}
That would hide every table on a page if you added the class "foo" to body, like this:
document.body.className += " foo";
...and then show the tables again if you removed it:
document.body.className =
document.body.className.replace(/\bfoo\b/, '');
Live example
Naturally, that selector can be a lot more discerning:
body.foo div.magic > table {
display: none;
}
That would only hide table elements that were immediate children of a div with the class "magic" (and only when body had the class "foo").
Off-topic: If the approach above doesn't suit (and it doesn't suit a lot of situations), JavaScript libraries like jQuery, Prototype, YUI, Closure, or any of several others can make manipulating sets of elements (in the ways that Felix mentioned) dramatically easier than going it alone.
Option 1 -- Create a function
function hideDiv(divname) {
document.getElementById(divname).style.display = "none";
}
Option 2 -- Hide a parent element
If all of the elements can be put inside of a parent element or already are, you can simply hide that parent element.
Option 3 -- Use a framework
A javascript framework like jQuery or MooTools will have a convenient coding convention such as .hide()
jQuery: -- see http://api.jquery.com/hide/
mooTools -- see http://mootools.net/docs/more/Element/Element.Shortcuts
Also, frameworks have tools for more complex situations and will allow you to select children of elements or a particular class and iterate through them. They can come in very handy when working with a page that has dynamically created content.
`
// jQuery Example 1: class-hiding
$(".elementsToHide").hide()
// jQuery Example 2: hiding divs within element "#whatever"
$("div", "#whatever").each(function() {
$(this).hide();
});
If they all have the same parent/ancestor, hide the parent (if possible).
Get the references to that elements, put them into an array and loop over them.
var divsToHide = ["thisDiv", "thatDiv", "divName"];
for (var i=0; i<divsToHide.length; ++i)
{
var div = document.getElementById(divsToHide[i]);
if (div) div.style.display = "none";
}
Or, you could use a framework like jQuery, and give the hidden divs some attribute in common, like a class of "hidden". Then,
$(".hidden").hide();
Course, in that case, you could also just set display: none on the class via CSS.
If they are from the same class you could select all elements of that class and loop through them. If they are all of the same parent you can select all the children, loop through them, filter if necessary and hide them this way.
var names = ['divName1', 'divName2','divName3'];
for ( i in names ) document.getElementById(names[i]).style.display = "none";

alter divs css with javascript

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.

Categories

Resources