Assigning classes to elements through CSS - html

I'd like to tell the browser to assign certain CSS classes to elements matching a particular selector. Can I do it with pure CSS and if yes, how?
Example: I want all the h5 elements inside a div with id sidebar to have the class ui-corners-all

No, that isn't possible with pure CSS.
Only with JavaScript:
// jQuery
$("h5").addClass("ui-corners-all");
// Pure JavaScript
var elements = document.getElementsByTagName("h5");
for (var i=0; i<elements.length; i++)
{
var el = elements[i];
el.setAttribute( "class", el.getAttribute("class") + " ui-corners-all" );
}

There is no way to assign this value to those elements in pure CSS.
You would need to do:
#sidebar h5
{
}
Then copy all styles from ui-corners-all class into this.
Or alternatively, change your ui-corners-all CSS to:
.ui-corners-all, #sidebar h5
{
}

No, you can't. You can however use Javascript (jQuery recommended) to achieve this effect.

Related

primeng how to inline style checkbox?

How can I use the style input of p-checkbox to change the border and background color of a checkbox?
I already tried [style]="{'background': '#ff0000'}". But this only applies the style to the div which holds the actual checkbox. So its useless. Instead I need to change the border-color and background of the div which has the classes p-checkbox-box and p-highlight.
Note: I cant use CSS here because the colors are dynamic and dependant on the content.
You can use renderer2 to manipulate DOM elements and then add style:
Get all checkboxes using document.getElementsByClassName('p-checkbox-box')
Iterate over each element and add the style you want using renderer2.setStyle()
try this piece of code and add it in ngAfterViewInit():
let chkboxes = document.getElementsByClassName('p-checkbox-box')
for (let index = 0; index < chkboxes.length; index++) {
const element = chkboxes[index];
this._renderer2.setStyle(element,'background-color','#bf2222');
this._renderer2.setStyle(element,'border-color','#bf2222');
}

Can i use attributes of element to create style rules?

I'm noot good in english, so the title may seem a bit odd.
I want to use css function attr() like this:
I mean i have a container <div> and an inner <div> that i want to have width depending on data-width attribute. For example this would be great, but this doesnt work:
<div class="container">
<div data-width="70%">
</div
</div>
.container {
width: 600px;
height: 200px;
}
.container div {
width: attr(data-width);
height: 100%;
}
Is there any noJS way to use attributes like that?
UPDATE: Guys convinced me that the JS is the only way to do this :)
That's not a big problem (but that's bad. CSS, why youre so illogical? Is the difference between content:attr(data-width) and width: attr(data-width) so big ?).
One of the guys had an idea to go through the all elements with jQuery.
That's ok, but it is very... local? Don't know how to say it in english.
Anyway, i remaked his code a little bit and here it is:
allowed = ['width','color','float'];
$(document).ready(function () {
$('div').each(function (i, el) {
var data = $(el).data(),style = '';
if (!$.isEmptyObject(data)) {
$.each(data, function (attr, value) {
if (allowed.indexOf(attr) != - 1) {
style += attr + ': ' + value + '; ';
}
})
if (style.length != 0) {
$(el).attr('style', style);
}
}
})
})
Idea is simple:
1. We suppose that style we want to add to an element is the only one. I mean there are no scripts that will try to add some other styles,
2. We create an array of allowed attribute names, we need to avoid using wrong names at the style attribute, for example style="answerid: 30671428;",
3. We go through each element, save its data attributes in an object, check if object is empty, and if not - check every attribute if it is allowed, create a string that contains all styles that we need, and - finally - add our style string to the element as the content of style attribute.
That's all, thanks everybody
I would not advise to use CSS alone since it will not allow you to do what you're looking for... instead use a scripting language (in my case jQuery) to accomplish this functionality for you like so: jsFiddle
jQuery
jQuery(document).ready(function(){
var dataElem; // to store each data attribute we come accross
jQuery('div').each(function(){ //loop through each div (can be changed to a class preferably)
dataElem = jQuery(this); //get the current div
if(dataElem.data('width')){ //make sure it exists before anything further
dataElem.width(dataElem.data('width')); //set the element's width to the data attribute's value
dataElem.css("background-color", "yellow");
}
});
});
HTML
<p>The links with a data-width attribute gets a yellow background:</p>
<div>
w3schools.com
</div>
<div class="me" data-width="50"> <!-- change value to see the difference -->
disney.com
</div>
<div>
wikipedia.org
</div>
Notes on the above:
each, data, width.
Instead of doing data-width, use a class attribute. An html tag can have mutliple classes separated by spaces, so if you wanted to be very precise, you could set up as many classes as you need. For instance:
<div class="w70 h100">
</div>
Then in your css:
.w70{
width: 70%;
}
.h100{
height: 100%;
}
And so on.
Is there any noJS way to use attributes like that?
No, you cannot use CSS to set the width of the element to it's data-width attribute. CSS does not allow for this as attr() is only currently available for the CSS content property which is only available on css pseudo elements (::before and ::after).
How can you achieve this with as little javascript as possible?
This is extremely easy to do using the native host provided DOM API.
Select the elements using Document.querySelectorAll().
Iterate the elements and apply the styles using Element.style which can be retrieved from the data-width attribute using Element.dataset
(Demo)
var items = document.querySelectorAll('#container div'), item, i;
for(i = 0; (item = items[i]); i++) item.style.width = item.dataset.width;

Apply style to grandparent of the grandchild with specific value [duplicate]

This question already has answers here:
Is there a CSS parent selector?
(33 answers)
Closed 8 years ago.
I have the following code:
<div class="photos-wrapper" id="detailPhoto">
<div class="pseudo">
fixedTEXT
</div>
<div class="image-wrapper">
</div>
<div class="activites">
</div>
<div class="commentaire">
</div>
</div>
I want to include my own CSS style to this first and main <div class="photos-wrapper" id="detailPhoto"> but the only way to do this is by identify the grandchild selector i.e <a href="#/123456/"> because there are multiple occurrences of the same code.
Maybe it will be a bit more clear when I show what I tried:
a[href*="123456"] > div.pseudo > div.photos-wrapper[id^="detailPhoto"] {
display: none !important;
}
div.photos-wrapper[id^="detailPhoto"] < div.pseudo < a[href*="123456"] {
display: none !important;
}
That's the way I tried to do so but it obviously is not working.
The thing I am probably trying to do here is called a parent selector but I'm not quite sure.
#edit
Let's take a look on this code, it's actually more detailed:
http://jsfiddle.net/60ezqtL7/
The goal is to hide by display: none; style whole divs that are containing exactly the same values i.e. PHOTO 1
There's no need to use jQuery in this case (or many other cases).
detailPhoto.classList.toggle('hide', detailPhoto.querySelector('[href=#/123456]'))
As I mentioned in my comment to your answer, there is not parent or ancestor selecor. The easiest and most efficient way to to it via jQuery is the has() method.
$('#detailPhoto').has('a[href*="123456"]').hide(); // or use .addClass() instead
Use Google to host jquery for you.
Demo : I've used the class selector in the demo as id should be unique.
addClass Demo
UPDATE
Given your update and assuming you want to display 1 and only 1 of each photo, additional wrappers with photos with the same href will be hidden.
/*Loop through each link in div with cass psudo
in a div with class photos-wrapper*/
var found = {};
$(".photos-wrapper .pseudo a").each(function(){
var $this = $(this);
var href = $this.attr("href");
//if the href has been enountered before, hide the .photos-wrapper ancestor
if(found[href]){
$this.closest(".photos-wrapper").hide();
/*Other options:
Use Css direct
$this.closest(".photos-wrapper").css("display", "none");
Assign a duplicate class, then style that class ass appropriate
$this.closest(".photos-wrapper").addClass("duplicate");
*/
}else{
//otherwise add it to the array of what has been found
found[href] = true;
}
});
Demo
If you're not familiar with jquery, make sure to read up on how it is implemented and the purpose of $(document).ready();
Update 2
To hide all containers with replicated href use:
//Loop through each a tag
$(".photos-wrapper .pseudo a").each(function () {
var $this = $(this);
//Get the href
var href = $this.attr("href");
//Check if more than one exists
if ($('.photos-wrapper .pseudo a[href="' + href + '"]').size() > 1) {
//Hide all .photo-wrapper containers that have the replicated href
$('.photos-wrapper .pseudo a[href="' + href + '"]').closest(".photos-wrapper").hide();
}
});
Another Demo
I still suggest removing duplicates server-side if at all possible.
On a complete side note, the <center> tag was depreciated back at HTML4 and should no longer be used. Use CSS instead. There are pleanty of examples out there on how to center content using CSS.
At this time there is not a way to do this with only CSS, but you can do it easily with JQuery. This will search the descendants of #detailPhoto and hide the href (set it to display: none;).
<script>
$(function() {
$('#detailPhoto').find('a[href$="#/123456/"]').hide();
});
</script>
To search parents, you'd use this.
<script>
$(function() {
$('a[href$="#/123456/"]').closest('#detailPhoto').hide();
});
</script>
To use this you will also need the JQuery library added to the head of your document.
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

edit css style of an element with a space in its class name

I'm creating a tumblr them and I have to write an external CSS file but I am having trouble editing the css style of the post elements.
This its structure:
<li class="post quote">
{other code}
</li>
The problem is that the class name has a space in it.
How would I create a CSS class to access this? And yes, I know I can just put a style attribute in the element tag but I was kind of hoping for another option.
The problem is that the class name has a space in it.
This is not possible in CSS. What you are doing is giving the element two classes.
You can address them such:
.post.quote { .... }
but in your case, it's probably better to use a valid separator like
post_quote
This element actually has two classes - it is marked with both the post class and the quote class. So, you can use the following selectors to access it:
// css
.post { ... } // elements with the post class
.quote { ... } // elements with the quote class
// jQuery
var postLis = $('.post');
var quoteLis = $('.quote');
You can also stack selectors to return all elements which meet all conditions in the selector, by including the different selectors together:
// css
.post.quote { ... } // elements with both the post and quote classes
// jQuery
var postAndQuoteLis = $('.post.quote');
This might work:
$('li').each(function() {
if($(this).attr('class').indexOf(" ")>-1) {
$(this).css('border','1px solid #ff0000')
}
}

Set selected option via CSS?

Is it possible to set the selected attribute of an option tag via a CSS class?
I'm wondering if something like the following is possible in a stylesheet:
option.selected {
selected: true;
}
Then in HTML:
<option class="selected">
Which would have the same effect as setting the selected attribute. Is this technique possible?
Nope, CSS only alters the presentation, not the content (although CSS3 does support some modification of content, but not the selection of values.) You'll need to use JavaScript if you can't modify the HTML directly.
option[selected] {background-color:skyblue;color:white;}
in case you want to show the previous marked selection - independend of the changes from the user after displaying a result, the old selected remain sykblue, the new changes are in darkblue.
Not via CSS, but it can be accomplished via javascript.
function setSelects() {
var allSelects = document.getElementsByTagName("select");
for (var i = 0; i < allSelects.length; i++) {
for (var j = 0; j < allSelects[i].options.length; j++) {
if (allSelects[i].options[j].className == "selected") {
allSelects[i].selectedIndex = j;
}
}
}
}
window.onload = setSelects;
As other people have pointed out, I'm not sure why you'd want to do it via a CSS class in the first place.
If you use JQuery then you can do something very much along those lines, but not CSS on its own.
Yes it is possible, but I am not sure about IE
Below code will change style for default selected item.
<style>
option[selected="selected"] {
color:red;
font-weight:bold
}
</style>
<select>
<option value="1">Txt</option>
<option value="2" selected="selected">Another Txt</option>
</select>
Selected is not a CSS property. See the spec at http://www.w3.org/TR/CSS2/propidx.html.