Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Created November 13, 2018 17:01
Show Gist options
  • Save anushshukla/2cde6336d43b6e2efd3a160cf1e1d870 to your computer and use it in GitHub Desktop.
Save anushshukla/2cde6336d43b6e2efd3a160cf1e1d870 to your computer and use it in GitHub Desktop.
Helpful Prototypes #js
Element.prototype.getAncestorByClassName = function(className){
var el = this;
while ((el = el.parentNode)) {
if(typeof el.className === "string" && el.className.match(className)) {
return el;
}
}
}
Element.prototype.getClass = function(className){
if(this.nodeName.match(/svg|circle/)) {
return this.className.baseVal;
}
return this.className;
}
Element.prototype.hasClass = function(className){
return this.getClass().match(className);
}
Element.prototype.addClass = function(className){
if(this.hasClass(className)) {
return;
}
this.className += " " + className;
}
Element.prototype.removeClass = function(className){
this.className = this.className.replace(className, '');
}
Element.prototype.replaceClass = function(oldClassName, newClassName){
this.className = this.className.replace(oldClassName, newClassName);
}
Element.prototype.hide = function(){
this.style.display = "none";
}
Element.prototype.show = function(displayStyle){
if(!displayStyle) {
displayStyle = 'block';
}
this.style.display = displayStyle;
}
Element.prototype.replaceOrAddClass = function(oldClassName, newClassName){
this.replaceClass(oldClassName, newClassName);
this.addClass(newClassName);
}
if (typeof HTMLDocument !== 'undefined') {
HTMLDocument.prototype.getElementByClassName = getElementByClassName;
} else {
Document.prototype.getElementByClassName = getElementByClassName;
}
Element.prototype.getChildByClassName = function(className){
var children = this.children || this.childNodes;
for (var i = 0; i < children.length; i++) {
if (children[i].nodeType == 3) {
continue;
}
var child = children[i];
if (child.hasClass(className)) {
return children[i];
}
var found = child.getChildByClassName(className);
if(found) {
return found;
}
}
return;
}
String.prototype.toUpperCaseWord = function(){
return this.replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment