Can someone help me write this line of jQuery in javascript. It applies a single rule of styling to a class.
$('.dataCard').css('visibilty', 'visible !important');
As !important doesn't apply when setting styles with javascript, it would be something like this
var elems = document.querySelectorAll('.dataCard');
for (var i=elems.length; i--;) {
elems[i].style.visibility = 'visible';
}
If you want to make a general purpose function that can replace what you had in jQuery, you could do this:
function setStyle(elemOrSelector, prop, val) {
var items;
if (typeof elemOrSelector === "string") {
// run selector query
items = document.querySelectorAll(elemOrSelector);
} else if (elemOrSelector.nodeName) {
// must be single DOM object
items = [elemOrSelector];
} else if (elemOrSelector.length)
// must be an array or nodeList
items = elemOrSelector;
} else {
// don't know what it is
return;
}
for (var i = 0; i < items.length; i++) {
items[i].style[prop] = val;
}
}
setStyle('.dataCard', "visibility", "visible");
This general purpose function allows you to pass either a DOM element, an array like list of DOM elements or a selector string.
If you don't want the general purposeness, then you can just use this:
function setStyle(selector, prop, val) {
var items = document.querySelectorAll(selector);
for (var i = 0; i < items.length; i++) {
items[i].style[prop] = val;
}
}
setStyle('.dataCard', "visibility", "visible");
Related
Is there a way to determine whether or not a css class exists using JavaScript?
This should be possible to do using the document.styleSheets[].rules[].selectorText and document.styleSheets[].imports[].rules[].selectorText properties. Refer to MDN documentation.
function getAllSelectors() {
var ret = [];
for(var i = 0; i < document.styleSheets.length; i++) {
var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
for(var x in rules) {
if(typeof rules[x].selectorText == 'string') ret.push(rules[x].selectorText);
}
}
return ret;
}
function selectorExists(selector) {
var selectors = getAllSelectors();
for(var i = 0; i < selectors.length; i++) {
if(selectors[i] == selector) return true;
}
return false;
}
Based on the answer, I created a javascript function for searching for a CSS class in the browser's memory -
var searchForCss = function (searchClassName) {
for (let i = 0; i < document.styleSheets.length; i++) {
let styleSheet = document.styleSheets[i];
try {
for (let j = 0; j < styleSheet.cssRules.length; j++) {
let rule = styleSheet.cssRules[j];
// console.log(rule.selectorText)
if (rule.selectorText && rule.selectorText.includes(searchClassName)) {
console.log('found - ', rule.selectorText, ' ', i, '-', j);
}
}
if (styleSheet.imports) {
for (let k = 0; k < styleSheet.imports.length; k++) {
let imp = styleSheet.imports[k];
for (let l = 0; l < imp.cssRules.length; l++) {
let rule = imp.cssRules[l];
if (
rule.selectorText &&
rule.selectorText.includes(searchClassName)
) {
console.log('found - ',rule.selectorText,' ',i,'-',k,'-',l);
}
}
}
}
} catch (err) {}
}
};
searchForCss('my-class-name');
This will print a line for each occurrence of the class name in any of the rules in any of the stylesheets.
Ref - Search for a CSS class in the browser memory
Here is my solution to this. I'm essentially just looping through document.styleSheets[].rules[].selectorText as #helen suggested.
/**
* This function searches for the existence of a specified CSS selector in a given stylesheet.
*
* #param (string) styleSheetName - This is the name of the stylesheet you'd like to search
* #param (string) selector - This is the name of the selector you'd like to find
* #return (bool) - Returns true if the selector is found, false if it's not found
* #example - console.log(selectorInStyleSheet ('myStyleSheet.css', '.myClass'));
*/
function selectorInStyleSheet(styleSheetName, selector) {
/*
* Get the index of 'styleSheetName' from the document.styleSheets object
*/
for (var i = 0; i < document.styleSheets.length; i++) {
var thisStyleSheet = document.styleSheets[i].href ? document.styleSheets[i].href.replace(/^.*[\\\/]/, '') : '';
if (thisStyleSheet == styleSheetName) { var idx = i; break; }
}
if (!idx) return false; // We can't find the specified stylesheet
/*
* Check the stylesheet for the specified selector
*/
var styleSheet = document.styleSheets[idx];
var cssRules = styleSheet.rules ? styleSheet.rules : styleSheet.cssRules;
for (var i = 0; i < cssRules.length; ++i) {
if(cssRules[i].selectorText == selector) return true;
}
return false;
}
This function offers a speed improvement over other solutions in that we are only searching the stylesheet passed to the function. The other solutions loop through all the stylesheets which is in many cases unnecessary.
/*
You can loop through every stylesheet currently loaded and return an array of all the defined rules for any selector text you specify, from tag names to class names or identifiers.
Don't include the '#' or '.' prefix for an id or class name.
Safari used to skip disabled stylesheets, and there may be other gotchas out there, but reading the rules generally works better across browsers than writing new ones.
*/
function getDefinedCss(s){
if(!document.styleSheets) return '';
if(typeof s== 'string') s= RegExp('\\b'+s+'\\b','i'); // IE capitalizes html selectors
var A, S, DS= document.styleSheets, n= DS.length, SA= [];
while(n){
S= DS[--n];
A= (S.rules)? S.rules: S.cssRules;
for(var i= 0, L= A.length; i<L; i++){
tem= A[i].selectorText? [A[i].selectorText, A[i].style.cssText]: [A[i]+''];
if(s.test(tem[0])) SA[SA.length]= tem;
}
}
return SA.join('\n\n');
}
getDefinedCss('p')//substitute a classname or id if you like
the latest item in the cascade is listed first.
Add this Condition Above
if (!document.getElementsByClassName('className').length){
//class not there
}
else{
//class there
}
If want to check on a element Just use
element.hasClassName( className );
also you can use on a ID
document.getElementById("myDIV").classList.contains('className');
Good Luck !!!
Building on Helen's answer, I came up with this:
//**************************************************************************
//** hasStyleRule
//**************************************************************************
/** Returns true if there is a style rule defined for a given selector.
* #param selector CSS selector (e.g. ".deleteIcon", "h2", "#mid")
*/
var hasStyleRule = function(selector) {
var hasRule = function(selector, rules){
if (!rules) return false;
for (var i=0; i<rules.length; i++) {
var rule = rules[i];
if (rule.selectorText){
var arr = rule.selectorText.split(',');
for (var j=0; j<arr.length; j++){
if (arr[j].indexOf(selector) !== -1){
var txt = trim(arr[j]);
if (txt===selector){
return true;
}
else{
var colIdx = txt.indexOf(":");
if (colIdx !== -1){
txt = trim(txt.substring(0, colIdx));
if (txt===selector){
return true;
}
}
}
}
}
}
}
return false;
};
var trim = function(str){
return str.replace(/^\s*/, "").replace(/\s*$/, "");
};
for (var i=0; i<document.styleSheets.length; i++){
var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
if (hasRule(selector, rules)){
return true;
}
var imports = document.styleSheets[i].imports;
if (imports){
for (var j=0; j<imports.length; j++){
rules = imports[j].rules || imports[j].cssRules;
if (hasRule(selector, rules)) return true;
}
}
}
return false;
};
You could check and see if an object of the style your are looking for already exists. If it does then the css class must exist because an object is using it. For example if you wanted to make sure that distinctly named svg objects each have their own style:
function getClassName(name) {
//Are there any elements which use a style named 'name' ?
if (document.getElementsByClassName(name).length === 0){
//There are none yest, let's make a new style and add it
var style = document.createElement('style');
style.type = 'text/css';
//Where you might provide your own hash function or rnd color
style.innerHTML = '.'+name+' { fill: #' + getHashColor(name) + '; background: #F495A3; }';
//Add the style to the document
document.getElementsByTagName('head')[0].appendChild(style);
}
return name;
}
Note that this is NOT a good approach if you are looking for a style which isn't necessarily used in your document.
if ($(".class-name").length > 0) {
}
That is a nice way to check the class in HTML by using javascript
Oneliner:
[].slice.call(document.styleSheets)
.reduce( (prev, styleSheet) => [].slice.call(styleSheet.cssRules))
.reduce( (prev, cssRule) => prev + cssRule.cssText)
.includes(".someClass")
function getAllSelectors() {
var ret = {};
for(var i=0;i<document.styleSheets.length;i++){
try {
var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
for(var x in rules) {
if(typeof rules[x].selectorText === 'string'){
if(ret[rules[x].selectorText] === undefined){
ret[rules[x].selectorText] = rules[x].style.cssText;
}
else {
ret[rules[x].selectorText] = ret[rules[x].selectorText] + ' ' + rules[x].style.cssText;
}
}
}
}
catch(error){
console.log(document.styleSheets[i]);
}
}
return ret;
}
function selectorExists(selector) {
var selectors = getAllSelectors();
if(selectors[selector] !== undefined){
return true;
}
return false;
}
// var allSelectors = getAllSelectors();
I'm trying to hide elements with the same class name (float_form), but I'm also trying to use the script below to show them (all of the float_form class divs are initially hidden). I've looked at a lot of jquery solutions, but I can't seem to make any of them work for this.
function show(a) {
var e = document.getElementById(a);
if (!e)
return true;
if (e.style.display == "none") {
e.style.display = "block"
} else {
e.style.display = "none"
}
return true;
}
Edit: Sorry if it wasn't clear, I do not intend to use Jquery(and I know that this is not jquery). I am looking for a way to use javascript to recognize repeated classnames that are not in style= display:none; without compromising the show/hide ID element since there is a loop with the div id as the key. The html for the div looks like below, with {item.ID} being a while loop.
<div class="float_form" id="{item.ID}" style="display: none;">
vanilla javascript
function toggle(className, displayState){
var elements = document.getElementsByClassName(className)
for (var i = 0; i < elements.length; i++){
elements[i].style.display = displayState;
}
}
toggle('float_form', 'block'); // Shows
toggle('float_form', 'none'); // hides
jQuery:
$('.float_form').show(); // Shows
$('.float_form').hide(); // hides
If you're looking into jQuery, then it's good to know that you can use a class selector inside the parameters of $ and call the method .hide().
$('.myClass').hide(); // all elements with the class myClass will hide.
But if it's a toggle you're looking for, use .toggle();
But here's my take on a good toggle without using jQuery:
function toggle( selector ) {
var nodes = document.querySelectorAll( selector ),
node,
styleProperty = function(a, b) {
return window.getComputedStyle ? window.getComputedStyle(a).getPropertyValue(b) : a.currentStyle[b];
};
[].forEach.call(nodes, function( a, b ) {
node = a;
node.style.display = styleProperty(node, 'display') === 'block' ? 'none' : 'block';
});
}
toggle( '.myClass' );
Demo here (Click "Render" to run): http://jsbin.com/ofusad/2/edit#javascript,html
Using jquery
$(".float_form").each(function(){
if($(this).css("display") == "none"){
$(this).show();
}else{
$(this).hide();
}
});
No jQuery needed
const toggleNone = className => {
let elements = document.getElementsByClassName(className)
for (let i = 0; i < elements.length; i++){
if (elements[i].style.display === "none") {
elements[i].style.display = "";
} else {
elements[i].style.display = "none";
}
}
}
const toggleVisibility = className => {
let elements = document.getElementsByClassName(className)
for (let i = 0; i < elements.length; i++){
let elements = document.getElementsByClassName(className);
if (elements[i].style.visibility === "hidden") {
elements[i].style.visibility = "";
} else {
elements[i].style.visibility = "hidden";
}
}
}
// run
toggleNone('your-class-name-here'); // toggles remove
// or run
toggleVisibility('your-class-name-here'); // toggles hide
Answer provided in ES6 syntax but easily can be converted to ES5 if you wish
Try :
function showClass(a){
var e = [];
var e = getElementsByClassName(a);
for(i in e ){
if(!e[i])return true;
if(e[i].style.display=="none"){
e[i].style.display="block"
} else {
e[i].style.display="none"
}
}
return true;
}
demo : showClass("float_form");
I'm writing a script for CasperJS. I need to click on the link that contains a span with "1". In jQuery can be used :contains('1'), but what the solution is for selectors in pure Javascript?
HTML: <a class="swchItem"><span>1</span></a><a class="swchItem"><span>2</span></a>
jQuery variant: $('a .swchItem span:contains("1")')
UPD CasperJS code:
casper.then(function () {
this.click('a .swchItem *select span with 1*')
})
Since 0.6.8, CasperJS offers XPath support, so you can write something like this:
var x = require('casper').selectXPath;
casper.then(function() {
this.click(x('//span[text()="1"]'))
})
Hope this helps.
Try the following. The difference between mine and gillesc's answer is I'm only getting a tags with the classname you specified, so if you have more a tags on the page without that class, you could have unexpected results with his answer. Here's mine:
var aTags = document.getElementsByTagName("a");
var matchingTag;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].className == "swchItem") {
for (var j = 0; j < aTags[i].childNodes.length; j++) {
if (aTags[i].childNodes[j].innerHTML == "1") {
matchingTag = aTags[i].childNodes[j];
}
}
}
}
var spans = document.getElementsByTagName('span'),
len = spans.length,
i = 0,
res = [];
for (; i < len; i++) {
if (spans.innerHTML == 1) res.push(spans[i]);
}
Is what you have to do unless the browser support native css queries.
jQuery is javascript. There are also a number of selector engines available as alternatives.
If you want to do it from scratch, you can use querySelectorAll and then look for appropriate content (assuming the content selector isn't implemented) and if that's not available, implement your own.
That would mean getting elements by tag name, filtering on the class, then looking for internal spans with matching content, so:
// Some helper functions
function hasClass(el, className) {
var re = new RegExp('(^|\\s)' + className + '(\\s|$)');
return re.test(el.className);
}
function toArray(o) {
var a = [];
for (var i=0, iLen=o.length; i<iLen; i++) {
a[i] = o[i];
}
return a;
}
// Main function
function getEls() {
var result = [], node, nodes;
// Collect spans inside A elements with class swchItem
// Test for qsA support
if (document.querySelectorAll) {
nodes = document.querySelectorAll('a.swchItem span');
// Otherwise...
} else {
var as = document.getElementsByTagName('a');
nodes = [];
for (var i=0, iLen=as.length; i<iLen; i++) {
a = as[i];
if (hasClass(a, 'swchItem')) {
nodes = nodes.concat(toArray(a.getElementsByTagName('span')));
}
}
}
// Filter spans on content
for (var j=0, jLen=nodes.length; j<jLen; j++) {
node = nodes[j];
if ((node.textContent || node.innerHTML).match('1')) {
result.push(node);
}
}
return result;
}
I am having issues figuring out how to resolve the getElementsByClassName issue in IE. How would I best implement the robert nyman (can't post the link to it since my rep is only 1) resolution into my code? Or would a jquery resolution be better? my code is
function showDesc(name) {
var e = document.getElementById(name);
//Get a list of elements that have a class name of service selected
var list = document.getElementsByClassName("description show");
//Loop through those items
for (var i = 0; i < list.length; ++i) {
//Reset all class names to description
list[i].className = "description";
}
if (e.className == "description"){
//Set the css class for the clicked element
e.className += " show";
}
else{
if (e.className == "description show"){
return;
}
}}
and I am using it on this page dev.msmnet.com/services/practice-management to show/hide the description for each service (works in Chrome and FF). Any tips would be greatly appreciated.
I was curious to see what a jQuery version of your function would look like, so I came up with this:
function showDesc(name) {
var e = $("#" + name);
$(".description.show").removeClass("show");
if(e.attr("class") == "description") {
e.addClass("show");
} else if(e.hasClass("description") && e.hasClass("show")) {
return;
}
}
This should support multiple classes.
function getElementsByClassName(findClass, parent) {
parent = parent || document;
var elements = parent.getElementsByTagName('*');
var matching = [];
for(var i = 0, elementsLength = elements.length; i < elementsLength; i++){
if ((' ' + elements[i].className + ' ').indexOf(findClass) > -1) {
matching.push(elements[i]);
}
}
return matching;
}
You can pass in a parent too, to make its searching the DOM a bit faster.
If you want getElementsByClassName('a c') to match HTML <div class="a b c" /> then try changing it like so...
var elementClasses = elements[i].className.split(/\s+/),
matchClasses = findClass.split(/\s+/), // Do this out of the loop :)
found = 0;
for (var j = 0, elementClassesLength = elementClasses.length; j < elementClassesLength; j++) {
if (matchClasses.indexOf(elementClasses[j]) > -1) {
found++;
}
}
if (found == matchClasses.length) {
// Push onto matching array
}
If you want this function to only be available if it doesn't already exist, wrap its definition with
if (typeof document.getElementsByClassName != 'function') { }
Even easier jQuery solution:
$('.service').click( function() {
var id = "#" + $(this).attr('id') + 'rt';
$('.description').not(id).hide();
$( id ).show();
}
Why bother with a show class if you are using jQuery?
Heres one I put together, reliable and possibly the fastest. Should work in any situation.
function $class(className) {
var children = document.getElementsByTagName('*') || document.all;
var i = children.length, e = [];
while (i--) {
var classNames = children[i].className.split(' ');
var j = classNames.length;
while (j--) {
if (classNames[j] == className) {
e.push(children[i]);
break;
}
}
}
return e;
}
I used to implement HTMLElement.getElementByClassName(), but at least Firefox and Chrome, only find the half of the elements when those elements are a lot, instead I use something like (actually it is a larger function):
getElmByClass(clm, parent){
// clm: Array of classes
if(typeof clm == "string"){ clm = [clm] }
var i, m = [], bcl, re, rm;
if (document.evaluate) { // Non MSIE browsers
v = "";
for(i=0; i < clm.length; i++){
v += "[contains(concat(' ', #"+clc+", ' '), ' " + base[i] + " ')]";
}
c = document.evaluate("./"+"/"+"*" + v, parent, null, 5, null);
while ((node = c.iterateNext())) {
m.push(node);
}
}else{ // MSIE which doesn't understand XPATH
v = elm.getElementsByTagName('*');
bcl = "";
for(i=0; i < clm.length; i++){
bcl += (i)? "|":"";
bcl += "\\b"+clm[i]+"\\b";
}
re = new RegExp(bcl, "gi");
for(i = 0; i < v.length; i++){
if(v.className){
rm = v[i].className.match(bcl);
if(rm && rm.length){ // sometimes .match returns an empty array so you cannot use just 'if(rm)'
m.push(v[i])
}
}
}
}
return m;
}
I think there would be a faster way to iterate without XPATH, because RegExp are slow (perhaps a function with .indexOf, it shuld be tested), but it is working well
You can replace getElementsByClassName() with the following:
function getbyclass(n){
var elements = document.getElementsByTagName("*");
var result = [];
for(z=0;z<elements.length;z++){
if(elements[z].getAttribute("class") == n){
result.push(elements[z]);
}
}
return result;
}
Then you can use it like this:
getbyclass("description") // Instead of document.getElementsByClassName("description")
Is there a way to determine whether or not a css class exists using JavaScript?
This should be possible to do using the document.styleSheets[].rules[].selectorText and document.styleSheets[].imports[].rules[].selectorText properties. Refer to MDN documentation.
function getAllSelectors() {
var ret = [];
for(var i = 0; i < document.styleSheets.length; i++) {
var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
for(var x in rules) {
if(typeof rules[x].selectorText == 'string') ret.push(rules[x].selectorText);
}
}
return ret;
}
function selectorExists(selector) {
var selectors = getAllSelectors();
for(var i = 0; i < selectors.length; i++) {
if(selectors[i] == selector) return true;
}
return false;
}
Based on the answer, I created a javascript function for searching for a CSS class in the browser's memory -
var searchForCss = function (searchClassName) {
for (let i = 0; i < document.styleSheets.length; i++) {
let styleSheet = document.styleSheets[i];
try {
for (let j = 0; j < styleSheet.cssRules.length; j++) {
let rule = styleSheet.cssRules[j];
// console.log(rule.selectorText)
if (rule.selectorText && rule.selectorText.includes(searchClassName)) {
console.log('found - ', rule.selectorText, ' ', i, '-', j);
}
}
if (styleSheet.imports) {
for (let k = 0; k < styleSheet.imports.length; k++) {
let imp = styleSheet.imports[k];
for (let l = 0; l < imp.cssRules.length; l++) {
let rule = imp.cssRules[l];
if (
rule.selectorText &&
rule.selectorText.includes(searchClassName)
) {
console.log('found - ',rule.selectorText,' ',i,'-',k,'-',l);
}
}
}
}
} catch (err) {}
}
};
searchForCss('my-class-name');
This will print a line for each occurrence of the class name in any of the rules in any of the stylesheets.
Ref - Search for a CSS class in the browser memory
Here is my solution to this. I'm essentially just looping through document.styleSheets[].rules[].selectorText as #helen suggested.
/**
* This function searches for the existence of a specified CSS selector in a given stylesheet.
*
* #param (string) styleSheetName - This is the name of the stylesheet you'd like to search
* #param (string) selector - This is the name of the selector you'd like to find
* #return (bool) - Returns true if the selector is found, false if it's not found
* #example - console.log(selectorInStyleSheet ('myStyleSheet.css', '.myClass'));
*/
function selectorInStyleSheet(styleSheetName, selector) {
/*
* Get the index of 'styleSheetName' from the document.styleSheets object
*/
for (var i = 0; i < document.styleSheets.length; i++) {
var thisStyleSheet = document.styleSheets[i].href ? document.styleSheets[i].href.replace(/^.*[\\\/]/, '') : '';
if (thisStyleSheet == styleSheetName) { var idx = i; break; }
}
if (!idx) return false; // We can't find the specified stylesheet
/*
* Check the stylesheet for the specified selector
*/
var styleSheet = document.styleSheets[idx];
var cssRules = styleSheet.rules ? styleSheet.rules : styleSheet.cssRules;
for (var i = 0; i < cssRules.length; ++i) {
if(cssRules[i].selectorText == selector) return true;
}
return false;
}
This function offers a speed improvement over other solutions in that we are only searching the stylesheet passed to the function. The other solutions loop through all the stylesheets which is in many cases unnecessary.
/*
You can loop through every stylesheet currently loaded and return an array of all the defined rules for any selector text you specify, from tag names to class names or identifiers.
Don't include the '#' or '.' prefix for an id or class name.
Safari used to skip disabled stylesheets, and there may be other gotchas out there, but reading the rules generally works better across browsers than writing new ones.
*/
function getDefinedCss(s){
if(!document.styleSheets) return '';
if(typeof s== 'string') s= RegExp('\\b'+s+'\\b','i'); // IE capitalizes html selectors
var A, S, DS= document.styleSheets, n= DS.length, SA= [];
while(n){
S= DS[--n];
A= (S.rules)? S.rules: S.cssRules;
for(var i= 0, L= A.length; i<L; i++){
tem= A[i].selectorText? [A[i].selectorText, A[i].style.cssText]: [A[i]+''];
if(s.test(tem[0])) SA[SA.length]= tem;
}
}
return SA.join('\n\n');
}
getDefinedCss('p')//substitute a classname or id if you like
the latest item in the cascade is listed first.
Add this Condition Above
if (!document.getElementsByClassName('className').length){
//class not there
}
else{
//class there
}
If want to check on a element Just use
element.hasClassName( className );
also you can use on a ID
document.getElementById("myDIV").classList.contains('className');
Good Luck !!!
Building on Helen's answer, I came up with this:
//**************************************************************************
//** hasStyleRule
//**************************************************************************
/** Returns true if there is a style rule defined for a given selector.
* #param selector CSS selector (e.g. ".deleteIcon", "h2", "#mid")
*/
var hasStyleRule = function(selector) {
var hasRule = function(selector, rules){
if (!rules) return false;
for (var i=0; i<rules.length; i++) {
var rule = rules[i];
if (rule.selectorText){
var arr = rule.selectorText.split(',');
for (var j=0; j<arr.length; j++){
if (arr[j].indexOf(selector) !== -1){
var txt = trim(arr[j]);
if (txt===selector){
return true;
}
else{
var colIdx = txt.indexOf(":");
if (colIdx !== -1){
txt = trim(txt.substring(0, colIdx));
if (txt===selector){
return true;
}
}
}
}
}
}
}
return false;
};
var trim = function(str){
return str.replace(/^\s*/, "").replace(/\s*$/, "");
};
for (var i=0; i<document.styleSheets.length; i++){
var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
if (hasRule(selector, rules)){
return true;
}
var imports = document.styleSheets[i].imports;
if (imports){
for (var j=0; j<imports.length; j++){
rules = imports[j].rules || imports[j].cssRules;
if (hasRule(selector, rules)) return true;
}
}
}
return false;
};
You could check and see if an object of the style your are looking for already exists. If it does then the css class must exist because an object is using it. For example if you wanted to make sure that distinctly named svg objects each have their own style:
function getClassName(name) {
//Are there any elements which use a style named 'name' ?
if (document.getElementsByClassName(name).length === 0){
//There are none yest, let's make a new style and add it
var style = document.createElement('style');
style.type = 'text/css';
//Where you might provide your own hash function or rnd color
style.innerHTML = '.'+name+' { fill: #' + getHashColor(name) + '; background: #F495A3; }';
//Add the style to the document
document.getElementsByTagName('head')[0].appendChild(style);
}
return name;
}
Note that this is NOT a good approach if you are looking for a style which isn't necessarily used in your document.
if ($(".class-name").length > 0) {
}
That is a nice way to check the class in HTML by using javascript
Oneliner:
[].slice.call(document.styleSheets)
.reduce( (prev, styleSheet) => [].slice.call(styleSheet.cssRules))
.reduce( (prev, cssRule) => prev + cssRule.cssText)
.includes(".someClass")
function getAllSelectors() {
var ret = {};
for(var i=0;i<document.styleSheets.length;i++){
try {
var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
for(var x in rules) {
if(typeof rules[x].selectorText === 'string'){
if(ret[rules[x].selectorText] === undefined){
ret[rules[x].selectorText] = rules[x].style.cssText;
}
else {
ret[rules[x].selectorText] = ret[rules[x].selectorText] + ' ' + rules[x].style.cssText;
}
}
}
}
catch(error){
console.log(document.styleSheets[i]);
}
}
return ret;
}
function selectorExists(selector) {
var selectors = getAllSelectors();
if(selectors[selector] !== undefined){
return true;
}
return false;
}
// var allSelectors = getAllSelectors();