How can you determine if a css class exists with Javascript? - javascript

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

Related

detect if a certain class exists css (not a duplicate) [duplicate]

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

Get CSS class definition from chrome developer tools console

I would like to programatically retrieve a set of CSS class definitions from chrome developer tools. In effect similar to what is displayed in styles tab in the right hand side. The input needs to be a class name and the output should be all the styles defined in it.
I'm aware of getComputedStyle DOM method, but this doesn't separate into separate classes which I need.
This approach worked for me (stackoverflow.com/a/27527462/1023562):
/**
* Gets styles by a classname
*
* #notice The className must be 1:1 the same as in the CSS
* #param string className_
*/
function getStyle(className_) {
var styleSheets = window.document.styleSheets;
var styleSheetsLength = styleSheets.length;
for(var i = 0; i < styleSheetsLength; i++){
var classes = styleSheets[i].rules || styleSheets[i].cssRules;
var classesLength = classes.length;
for (var x = 0; x < classesLength; x++) {
if (classes[x].selectorText == className_) {
var ret;
if(classes[x].cssText){
ret = classes[x].cssText;
} else {
ret = classes[x].style.cssText;
}
if(ret.indexOf(classes[x].selectorText) == -1){
ret = classes[x].selectorText + "{" + ret + "}";
}
return ret;
}
}
}
}
It lets you invoke the javascript code in Chrome console like this:
console.log(getStyle('#heder_logo a'));
and get results like this:
> #heder_logo a { width: 200px; height: 114px; display: block; }.
I did have issues with some CSS files which were not on the same domain (they were pulled from CDN), but there are variety of proposals in that thread, so some should work for you.
Have adapted Ivan's answer in order to get a more complete result. This method will also return styles where the class is part for the selector
//Get all styles where the provided class is involved
//Input parameters should be css selector such as .myClass or #m
//returned as an array of tuples {selectorText:"", styleDefinition:""}
function getStyleWithCSSSelector(cssSelector) {
var styleSheets = window.document.styleSheets;
var styleSheetsLength = styleSheets.length;
var arStylesWithCSSSelector = [];
//in order to not find class which has the current name as prefix
var arValidCharsAfterCssSelector = [" ", ".", ",", "#",">","+",":","["];
//loop through all the stylessheets in the bor
for(var i = 0; i < styleSheetsLength; i++){
var classes = styleSheets[i].rules || styleSheets[i].cssRules;
var classesLength = classes.length;
for (var x = 0; x < classesLength; x++) {
//check for any reference to the class in the selector string
if(typeof classes[x].selectorText != "undefined"){
var matchClass = false;
if(classes[x].selectorText === cssSelector){//exact match
matchClass=true;
}else {//check for it as part of the selector string
//TODO: Optimize with regexp
for (var j=0;j<arValidCharsAfterCssSelector.length; j++){
var cssSelectorWithNextChar = cssSelector+ arValidCharsAfterCssSelector[j];
if(classes[x].selectorText.indexOf(cssSelectorWithNextChar)!=-1){
matchClass=true;
//break out of for-loop
break;
}
}
}
if(matchClass === true){
//console.log("Found "+ cssSelectorWithNextChar + " in css class definition " + classes[x].selectorText);
var styleDefinition;
if(classes[x].cssText){
styleDefinition = classes[x].cssText;
} else {
styleDefinition = classes[x].style.cssText;
}
if(styleDefinition.indexOf(classes[x].selectorText) == -1){
styleDefinition = classes[x].selectorText + "{" + styleDefinition + "}";
}
arStylesWithCSSSelector.push({"selectorText":classes[x].selectorText, "styleDefinition":styleDefinition});
}
}
}
}
if(arStylesWithCSSSelector.length==0) {
return null;
}else {
return arStylesWithCSSSelector;
}
}
In addition, I've made a function which collects the css style definitions to the sub-tree of a root node your provide (through a jquery selector).
function getAllCSSClassDefinitionsForSubtree(selectorOfRootElement){
//stack in which elements are pushed and poped from
var arStackElements = [];
//dictionary for checking already added css class definitions
var existingClassDefinitions = {}
//use jquery for selecting root element
var rootElement = $(selectorOfRootElement)[0];
//string with the complete CSS output
var cssString = "";
console.log("Fetching all classes used in sub tree of " +selectorOfRootElement);
arStackElements.push(rootElement);
var currentElement;
while(currentElement = arStackElements.pop()){
currentElement = $(currentElement);
console.log("Processing element " + currentElement.attr("id"));
//Look at class attribute of element
var classesString = currentElement.attr("class");
if(typeof classesString != 'undefined'){
var arClasses = classesString.split(" ");
//for each class in the current element
for(var i=0; i< arClasses.length; i++){
//fetch the CSS Styles for a single class. Need to append the . char to indicate its a class
var arStylesWithCSSSelector = getStyleWithCSSSelector("."+arClasses[i]);
console.log("Processing class "+ arClasses[i]);
if(arStylesWithCSSSelector != null){
//console.log("Found "+ arStylesWithCSSSelector.length + " CSS style definitions for class " +arClasses[i]);
//append all found styles to the cssString
for(var j=0; j< arStylesWithCSSSelector.length; j++){
var tupleStyleWithCSSSelector = arStylesWithCSSSelector[j];
//check if it has already been added
if(typeof existingClassDefinitions[tupleStyleWithCSSSelector.selectorText] === "undefined"){
//console.log("Adding " + tupleStyleWithCSSSelector.styleDefinition);
cssString+= tupleStyleWithCSSSelector.styleDefinition;
existingClassDefinitions[tupleStyleWithCSSSelector.selectorText] = true;
}else {
//console.log("Already added " + tupleStyleWithCSSSelector.styleDefinition);
}
}
}
}
}
//push all child elments to stack
if(currentElement.children().length>0){
arStackElements= arStackElements.concat(currentElement.children().toArray());
}
}
console.log("Found " + Object.keys(existingClassDefinitions).length + " CSS class definitions");
return cssString;
}
Note that if a class is defined several times with the same selector, the above function will only pick up the first.
Python script to search css file for a word once found read what is inbetween the curly braces. Quick and dirty way**

two delimiters output formatting javascript

I thought this would be easier, but running into a weird issue.
I want to split the following:
theList = 'firstword:subwordone;subwordtwo;subwordthree;secondword:subwordone;thirdword:subwordone;subwordtwo;';
and have the output be
firstword
subwordone
subwordtwo
subwordthree
secondword
subwordone
thirdword
subwordone
subwordtwo
The caveat is sometimes the list can be
theList = 'subwordone;subwordtwo;subwordthree;subwordfour;'
ie no ':' substrings to print out, and that would look like just
subwordone
subwordtwo
subwordthree
subwordfour
I have tried variations of the following base function, trying recursion, but either get into infinite loops, or undefined output.
function getUl(theList, splitOn){
var r = '<ul>';
var items = theList.split(splitOn);
for(var li in items){
r += ('<li>'+items[li]+'</li>');
}
r += '</ul>';
return r;
}
The above function is just my starting point and obviously doesnt work, just wanted to show what path I am going down, and to be shown the correct path, if this is totally off base.
It seems you need two cases, and the difference between the two is whether there is a : in your string.
if(theList.indexOf(':') == -1){
//Handle the no sublist case
} else {
//Handle the sublist case
}
Starting with the no sublist case, we develop the simple pattern:
var elements = theList.split(';');
for(var i = 0; i < elements.length; i++){
var element = elements[i];
//Add your element to your list
}
Finally, we apply that same pattern to come up with the implementation for the sublist case:
var elements = theList.split(';');
for(var i = 0; i < elements.length; i++){
var element = elements[i];
if(element.indexOf(':') == -1){
//Add your simple element to your list
} else {
var innerElements = element.split(':');
//Add innerElements[0] as your parent element
//Add innerElements[1] as your child element
//Increment i until you hit another element with ':', adding the single elements each increment as child elements.
//Decrement i so it considers the element with the ':' as a parent element.
}
}
Keep track of the current list to add items to, and create a new list when you find a colon in an item:
var baseParent = $('ul'), parent = baseParent;
$.each(theList.split(';'), function(i, e) {
if (e.length) {
var p = e.split(':');
if (p.length > 1) {
baseParent.append($('<li>').append($('<span>').text(p[0])).append(parent = $('<ul>')));
}
parent.append($('<li>').text(p[p.length - 1]));
}
});
Demo: http://jsfiddle.net/Guffa/eWQpR/
Demo for "1;2;3;4;": http://jsfiddle.net/Guffa/eWQpR/2/
There's probably a more elegant solution but this does the trick. (See edit below)
function showLists(text) {
// Build the lists
var lists = {'': []};
for(var i = 0, listKey = ''; i < text.length; i += 2) {
if(text[i + 1] == ':') {
listKey = text[i];
lists[listKey] = [];
} else {
lists[listKey].push(text[i]);
}
}
// Show the lists
for(var listName in lists) {
if(listName) console.log(listName);
for(var j in lists[listName]) {
console.log((listName ? ' ' : '') + lists[listName][j]);
}
}
}
EDIT
Another interesting approach you could take would be to start by breaking it up into sections (assuming text equals one of the examples you gave):
var lists = text.match(/([\w]:)?([\w];)+/g);
Then you have broken down the problem into simpler segments
for(var i = 0; i < lists.length; i++) {
var listParts = lists[i].split(':');
if(listParts.length == 1) {
console.log(listParts[0].split(';').join("\n"));
} else {
console.log(listParts[0]);
console.log(' ' + listParts[1].split(';').join("\n "));
}
}
The following snippet displays the list depending on your requirements
var str = 'subwordone;subwordtwo;subwordthree;';
var a = []; var arr = [];
a = str;
var final = [];
function split_string(a){
var no_colon = true;
for(var i = 0; i < a.length; i++){
if(a[i] == ':'){
no_colon = false;
var temp;
var index = a[i-1];
var rest = a.substring(i+1);
final[index] = split_string(rest);
return a.substring(0, i-2);
}
}
if(no_colon) return a;
}
function display_list(element, index, array) {
$('#results ul').append('<li>'+element+'</li>');
}
var no_colon_string = split_string(a).split(';');
if(no_colon_string){
$('#results').append('<ul><ul>');
}
no_colon_string.forEach(display_list);
console.log(final);
working fiddle here

jQuery ":contains()" analog for pure JS

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;
}

getElementsByClassName IE resolution issue

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")

Categories