I have an html code as below :
<div id="select_a_boundary" class="dataset_select2">Homes name</div>
I wrote a xpath expression for the same:
//div[#id = 'select_a_boundary' and #class = 'dataset_select2']
What will be the equivalent CSS Selectors for the same?
First of all if you are using id, you don't require to use class, secondly if you are willing yo select an element with an id select_a_boundary you can use
#select_a_boundary {
/* Styles goes here */
}
Demo
Note: Am not selecting the element which has that id and that class as
here, id is sufficient as it has to be unique, if you are using the id
for multiple elements than it's invalid
As per your comment
div[id=select_a_boundary][class=dataset_select2] {
color: red;
}
Demo X-Path Equivalent
Or an easier one (Credits: Jack)
#select_a_boundary.dataset_select2 {
color: red;
}
Note: Still I would recommend you to use #select_a_boundary is more
than enough
The equivalent of your expression in CSS is this:
#select_a_boundary.dataset_select2 {
/* whatever */
}
Because identifiers in a single document should be unique, you can even narrow it down to:
#select_a_boundary {
/* whatever */
}
One important thing to realize is that although XPath and CSS selectors have many similarities, they're two different things.
For instance, there's no XPath equivalent of :active or :hover for instance. Properly matching by class names is also more cumbersome with XPath.
On the other hand, CSS can't match things like "all paragraphs with an anchor child" which is trivial in XPath using //p[a].
Related
So I want to select the <div> element with the class .thisClass, but not any other elements with class of .thisClass:
<div class="thisClass"></div>
<p class="thisClass"></p>
CSS Selector by class name and tag: div.thisClass { ... }:
div.thisClass {
background-color: red;
}
<div class="thisClass">thisClass (div)</div>
<p class="thisClass">thisClass (p)</p>
But this is a bad way to write selectors:
Don’t qualify class rules with tag names
The previous concept also applies here. Though classes can be used many times on the same page, they are still more unique than a tag.
One convention you can use is to include the tag name in the class name. However, this may cost some flexibility; if design changes are made to the tag, the class names must be changed as well. (It’s best to choose strictly semantic names, as such flexibility is one of the aims of separate stylesheets.)
BAD
treecell.indented {…}
GOOD
.treecell-indented {…}
BEST
.hierarchy-deep {…}
Using JavaScript
document.querySelector('div.thisClass')
Using jQuery
$("div.thisClass")
Using CSS:
<style>
div.thisClass{}
</style>
The following code illustrates how to select the first class from the list of classes in both CSS and Javascript.
CSS
.thisClass:first-child {
/*css property*/
}
JAVASCRIPT:
var divElement = document.getElementsByClassName('thisClass')[0];
I have this elements in html:
<div id="element0div0">
div 0
</div>
<div id="element1div1">
div 1
</div>
<div id="element2div2">
div 2
</div>
can i use something like regex to apply css to element like element{n}div{n}?
There's no regular expression to differentiate between numbers and letters, but you can definitely approach a solution using:
div[id^=element][id*=div] {
/* css */
}
This has flaws in that this will match the following (and more) id strings:
elementdiv
elementSomeOtherStringdiv
elementdivSomeOtherString
I'd suggest, given the nature of your question, that it'd be far wiser to simply use a common class-name to all the elements to which you wish to apply a common style.
References:
CSS attribute-selectors.
Yes you can but you must use JavaScript.
Using jQuery :
$('div').filter(function() {
return this.id.match(/element[\d]+div[\d]+/)
}).css({color:'red'});
Using vanilla js :
for (var divs=document.getElementsByTagName('div'), i=0; i<divs.length; i++) {
if (divs[i].id.match(/element[\d]+div[\d]+/)) divs[i].style.color="red";
}
This assumes you need to do what you asked, that is apply a style to elements found by a regex applied to their id. Most often you can find simpler solutions, though, like adding a class when building the HTML.
Is there a way to apply a class by default to an element? Let's say for example I wanted to apply the class foo to all input elements:
.foo { ... }
My limited knowledge leads me to believe I need to mark that up every single time:
<input type='text' class='foo' />
<input type='password' class='foo' />
...
But, clearly I was hoping I could apply that class by default to all input elements in the CSS somehow. I look forward to your answers!
UPDATE
In an attempt to clarify myself, I do not want to duplicate the CSS that already exists for foo because I wouldn't want to have to change that in multiple places if I needed to change the style for foo. Further, I will be applying it to more than just all input elements.
If you mean you want to take all the styles in your .foo rule and apply them to inputs as well, just select both of them:
.foo, input { ... }
You can add a class to elements easily using a framework like jQuery:
$(document).ready(function() {
$('input').addClass('foo');
});
EDIT: To address your latest update...
If you want to "extend" a class for only certain conditions, you can add a second class for that case... e.g.:
<input class="foo bar" />
<style type="text/css">
.foo.bar {
color: #123;
}
</style>
This will only apply your elements that are both .foo and .bar, and won't affect global .foo styles, which will still be applied to all .foo elements (including these)
You could use javascript's document.getElementsByTagName(tag); function.
Example:
var tags = document.getElementsByTagName("input");
for(i = 0;i<tags.length;i++){
tags[i].className = "foo";
}
If you want to keep the current classes on it just make sure to do if(tags[i].className != ""){tags[i].className = tags[i].className + " foo";}. It'll carry over the current classes.
You might try looking into a stylesheet preprocessor like LESS or SASS. These will allow you to use variables and other tricks here and there to help you avoid duplicating CSS. There are Javascript implementations of these as well as server-side ones if you would like to process it before giving it to the user.
Of course, the CSS ends up with duplicate code anyway, but you wouldn't have to write the same thing twice yourself.
For example, in LESS:
.foo {
color: #222222;
padding: 10px;
}
input {
.foo;
}
input[type=text]{
color:#123;
}
this is the code to apply css
The HTML spec allows for periods (.) in an id:
<img id="some.id" />
However, using a CSS ID selector rule will not match correctly:
#some.id { color: #f00; }
The CSS spec for ID Selectors does not mention this case. So I assume it is using the combination of a tag name and class selector? For example, a CSS rule of a.className would apply to all anchor tags (<a>) with a class name of className, like <a class="className"></a>.
Is it possible to have an external CSS file rule that references an HTML element by its id that has a period in it?
I expect not since the CSS spec specifies that a CSS "identifier" does not include the period as a valid character. So is this a fundamental mismatch between HTML and CSS specs? Is my only alternative to use a different type of CSS selection? Can anyone smarter than I confirm or deny this?
(I would remove the period from the HTML id attribute to simplify things, but it is a system-generated id, so I don't have the ability to change it in this case.)
After digging through the specs some more, I found the CSS spec does allow for backslash (\) escaping like most languages.
So in my example, the following rule would match:
#some\.id {
color: #f00;
}
You could also use the attribute selector like this:
[id='some.id'] {
color: #f00;
}
Since you are using id, you can also use document.getElementById() which checks the id value as a normal string and not a CSS selector.
e.g. the following works too:
const myElem = document.getElementById("some.id");
The only drawback is, you can't limit the scope of search, like you could with querySelector e.g. someElement.querySelector().
but since Ids should always be unique, a document wide search with id is valid.
This should be simple, but I'm having trouble finding the search terms for it.
Let's say I have this:
<div class="a c">Foo</div>
<div class="b c">Bar</div>
In CSS, how can I create a selector that matches something that matches "(.a or .b) and .c"?
I know I could do this:
.a.c,.b.c {
/* CSS stuff */
}
But, assuming I'm going to have to do this sort of logic a lot, with a variety of logical combinations, is there a better syntax?
is there a better syntax?
No. CSS' or operator (,) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c.
Not yet, but there is the experimental :is() (formerly :matches()) pseudo-class selector that does just that:
:is(.a .b) .c {
/* style properties go here */
}
You can find more info on it here and here. Currently, most browsers support its initial version :any(), which works the same way, but will be replaced by :is(). We just have to wait a little more before using this everywhere (I surely will).
For those reading this >= 2021:
I found success using the :is() selector:
*:is(.a, .b).c{...}
If you have this:
<div class="a x">Foo</div>
<div class="b x">Bar</div>
<div class="c x">Baz</div>
And you only want to select the elements which have .x and (.a or .b), you could write:
.x:not(.c) { ... }
but that's convenient only when you have three "sub-classes" and you want to select two of them.
Selecting only one sub-class (for instance .a): .a.x
Selecting two sub-classes (for instance .a and .b): .x:not(.c)
Selecting all three sub-classes: .x
No. Standard CSS does not provide the kind of thing you're looking for.
However, you might want to look into LESS and SASS.
These are two projects which aim to extend default CSS syntax by introducing additional features, including variables, nested rules, and other enhancements.
They allow you to write much more structured CSS code, and either of them will almost certainly solve your particular use case.
Of course, none of the browsers support their extended syntax (especially since the two projects each have different syntax and features), but what they do is provide a "compiler" which converts your LESS or SASS code into standard CSS, which you can then deploy on your site.