jquery remove based on before content - javascript

Is it possible to write a JQuery function that will remove everything with a specific :before content.
here is an example statement to give you something to show me with code:
remove all elements in the document that have a :before pseudo element with content set to "delete me"

Mhh, you can try something like this:
var sheets = document.styleSheets;
var len = sheets.length;
var ba = /:before|:after/;
// Loop throught all stylesheets
for (var i = 0; i < len; i++) {
// work out which method to get the CSS rules
var sheet = sheets[i],
rules = sheet.cssRules || sheet.rules;
// Loop through all rules
for (var r = 0, rule; rule = rules[r++];) {
// if this rule uses one of the test selectors
if (rule.selectorText.match(ba)) {
if (rule.style.content.indexOf('delete me') !== -1) {
var elems = document.querySelectorAll(rule.selectorText.split(':')[0]);
for (var e = 0, elem; elem = elems[e++];) {
// remove the node
document.body.removeChild(elem);
}
}
}
}
}
http://fiddle.jshell.net/6m5kB/1/

there is simple answer just add class on that element with before and remove it through that class. pseudo-element does not exist in dom that why you cannot directly remove them through jquery or js

Related

Using Native JavaScript, change the title attribute of an object if it has a certain CSS class

So by using native javascript, how would I go about saying
"if this object has this css class, add this to the title attribute"
document.addEventListener("DOMContentLoaded", function(event) {
if(element.classlist.contains("current_page_item")||element.classlist.contains("current-page-ancestor")){
}
});
That is as far as I've gotten, I'm trying to stick to native javascript just so we don't have to load up any libraries and can keep the site as minimalist as possible.
You can use getElementsByClassName()
var x = document.getElementsByClassName("current_page_item");
Then loop and add title
x.forEach(function(element){
element.title = "title";
});
or
for (var i = 0; i < x.length; i++) {
x[i].title ="title";
}
To answer to your comment, to apply the title to the "a" element that is a child of the div element that has the "current_page_item" class
for (var i = 0; i < x.length; i++) {
var y = x[i].getElementsByTagName("a");
y[0].title = "title";
}
Similar to Rohit Shetty's reply, you could also use the querySelector:
let elements = document.querySelector(".current_page_item");
elements.forEach(function(e) {
e.title = "title";
);
You can use getElementsByClassName()
var x = document.getElementsByClassName("current_page_item");
for(var i=0;i<x.length;i++){
x[i].title += "BLAH";
}
I don't now if I have understood well.
But let's try.
First, locate the elements.
const nodes = document.querySelectorAll('.current_page_item, .current_page_item')
// nodes are the elements of one of the classes names
Then, apply the class Names to title.
function containsOfTheClasses (node) {
return classNames.some(x => node.classList.contains(x))
}
nodes.forEach(function (node) {
node.title += classNames.filter(containsOfTheClasses).join(' ')
})

javascript - remove inline event handlers / attributes of a node

Given an HTML node from the dom,
I need to remove all inline event handlers / attributes such as: onclick, onmouseover, onmousedown etc.
I know that:
document.getElementById("some_id").attributes
returns all the attributes, and I can eliminate some attriubtes, but then there is also attributes like: id, class, name etc.
How do I seperate the two types of attributes?
Completely different approches for solving the problem are also an option.
EDIT: I'm trying to remove only inline events,
and I also need to "save" them elsewhere before deletion, so cloning for complete disposal is not an option
Here you get all element attributes, make an array of em, check in for loop if any attribute starts with on. Then make an object with name/value of that inline event handler, push it into array, and at the end remove it from the node:
var el = document.getElementById("button1");
var listOfEvents=[];
var attributes = [].slice.call(el.attributes);
for (i = 0; i < attributes.length; i++){
var att= attributes[i].name;
if(att.indexOf("on")===0){
var eventHandlers={};
eventHandlers.attribute=attributes[i].name;
eventHandlers.value=attributes[i].value;
listOfEvents.push(eventHandlers);
el.attributes.removeNamedItem(att);
}
}
Check the below snippet
var el = document.getElementById("button1");
var listOfEvents = [];
var attributes = [].slice.call(el.attributes);
for (i = 0; i < attributes.length; i++) {
var att = attributes[i].name;
if (att.indexOf("on") === 0) {
console.log(att);
var eventHandlers = {};
eventHandlers.attribute = attributes[i].name;
eventHandlers.value = attributes[i].value;
listOfEvents.push(eventHandlers);
el.attributes.removeNamedItem(att);
}
}
console.log(listOfEvents);
/* logs [[object Object] {
attribute: "onmousedown",
value: "mouseDown();"
}, [object Object] {
attribute: "onmouseup",
value: "mouseUp();"
}, [object Object] {
attribute: "onclick",
value: "doSomething(this);"
}] */
<div>
<input id="button1" type="button" onmousedown="mouseDown();" onmouseup="mouseUp();" onclick="doSomething(this);" value="Click Me" />
</div>
Filter all attributes whose name starts with 'on'.
If you can name all the handlers you want to remove/check then this will work for you (it is basically searching for the attributes you give it and removes/saves them - added bonus, you can also remove some other attributes you want the same way, just add them to the list):
JSFiddle example
Btw, IDK wtf am i suppose to post as "obligatory code" when linking fiddleJS... just check the link I extracted the javascript here but you are missing html
var dataStorage = {};
function someFunction(num) {
alert(num);
};
function removeInlineHandlers(elementID) {
//Define all the attributes you want to remove;
var removeableAttributes = ["onclick", "onhover", "onmouseout"];
var attributes = document.getElementById(elementID).attributes;
var addFlag = true;
var i = 0;
var j = 0;
for (i = 0; i < attributes.length; i++) {
for (j = 0; j < removeableAttributes.length; j++) {
if (attributes[i].name == removeableAttributes[j]) {
// If this is the first attribute to be removed, add an object
// to track the data of removeals.
if (addFlag) {
dataStorage[elementID] = {};
addFlag = false;
}
dataStorage[elementID][attributes[i].name] = attributes[i].nodeValue;
document.getElementById(elementID).removeAttribute(attributes[i].name);
break;
}
}
}
}
function removeHandlersAndPrint() {
removeInlineHandlers("btn1");
removeInlineHandlers("btn2");
removeInlineHandlers("btn3");
removeInlineHandlers("btn4");
console.log(dataStorage);
}

How to get a ALL the css properties set on an element with jquery [duplicate]

Is there a way in jQuery to get all CSS from an existing element and apply it to another without listing them all?
I know it would work if they were a style attribute with attr(), but all of my styles are in an external style sheet.
A couple years late, but here is a solution that retrieves both inline styling and external styling:
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
Pass a jQuery object into css() and it will return an object, which you can then plug back into jQuery's $().css(), ex:
var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);
:)
Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.
Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.
jquery.getStyleObject.js:
/*
* getStyleObject Plugin for jQuery JavaScript Library
* From: http://upshots.org/?p=112
*/
(function($){
$.fn.getStyleObject = function(){
var dom = this.get(0);
var style;
var returns = {};
if(window.getComputedStyle){
var camelize = function(a,b){
return b.toUpperCase();
};
style = window.getComputedStyle(dom, null);
for(var i = 0, l = style.length; i < l; i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
};
return returns;
};
if(style = dom.currentStyle){
for(var prop in style){
returns[prop] = style[prop];
};
return returns;
};
return this.css();
}
})(jQuery);
Basic usage is pretty simple, but he's written a function for that as well:
$.fn.copyCSS = function(source){
  var styles = $(source).getStyleObject();
  this.css(styles);
}
Why not use .style of the DOM element? It's an object which contains members such as width and backgroundColor.
I had tried many different solutions. This was the only one that worked for me in that it was able to pick up on styles applied at class level and at style as directly attributed on the element. So a font set at css file level and one as a style attribute; it returned the correct font.
It is simple! (Sorry, can't find where I originally found it)
//-- html object
var element = htmlObject; //e.g document.getElementById
//-- or jquery object
var element = htmlObject[0]; //e.g $(selector)
var stylearray = document.defaultView.getComputedStyle(element, null);
var font = stylearray["font-family"]
Alternatively you can list all the style by cycling through the array
for (var key in stylearray) {
console.log(key + ': ' + stylearray[key];
}
#marknadal's solution wasn't grabbing hyphenated properties for me (e.g. max-width), but changing the first for loop in css2json() made it work, and I suspect performs fewer iterations:
for (var i = 0; i < css.length; i += 1) {
s[css[i]] = css.getPropertyValue(css[i]);
}
Loops via length rather than in, retrieves via getPropertyValue() rather than toLowerCase().

Javascript : How to get multiple span elements by ID?

I have several span elements which begin with the same id as shown below...
<span id="graph_machine"
<span id="graph_human"
<span id="graph_custom"
I would like to access these 3 Span elements as an array in my Javascript function..
var elems = document.getElementsById("graph*");
But getElementsById does not support returning multiple values. Any suggestions? Perhaps using a different function and some wildcard?
Thanks.
Use document.querySelectorAll:
var elems = document.querySelectorAll("[id^=graph]");
That will return a node list of any element with an id attribute whose value starts with "graph".
Try to get all span ID and then check if span ID starts with "graph"
var spans = document.getElementsByTagName("span");
var graphSpans = new Array();
for (var i = 0; i <= spans.length; i++) {
if (spans.id.startsWith("graph")) {
graphSpans.push(spans[i]);
}
}
Since startsWith method is not available in Javascript, so you need to add it to prototype as soon document is ready.
jQuery(document).ready(function() {
if (typeof String.prototype.startsWith != 'function') {
// see below for better implementation!
String.prototype.startsWith = function (str){
return this.indexOf(str) == 0;
};
}
}
If you are using jQuery you can use $( "span[id^='graph_']" )
You could get all spans and then check each ID individually:
var spans = document.getElementsByTagName("span");
var graphSpans = [];
for (var i = 0; i < spans.length; i++) {
if (spans[i].id.substring(0,5) === "graph") {
graphSpans.push(spans[i]);
}
}
http://jsfiddle.net/Sp6sp/
try this with jquery
$("span").each(function(){
console.log($(this).attr('id'));
});
Demo
http://jsfiddle.net/p5k2a/1/

jquery: Get full css property set as string from an element [duplicate]

Is there a way in jQuery to get all CSS from an existing element and apply it to another without listing them all?
I know it would work if they were a style attribute with attr(), but all of my styles are in an external style sheet.
A couple years late, but here is a solution that retrieves both inline styling and external styling:
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
Pass a jQuery object into css() and it will return an object, which you can then plug back into jQuery's $().css(), ex:
var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);
:)
Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.
Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.
jquery.getStyleObject.js:
/*
* getStyleObject Plugin for jQuery JavaScript Library
* From: http://upshots.org/?p=112
*/
(function($){
$.fn.getStyleObject = function(){
var dom = this.get(0);
var style;
var returns = {};
if(window.getComputedStyle){
var camelize = function(a,b){
return b.toUpperCase();
};
style = window.getComputedStyle(dom, null);
for(var i = 0, l = style.length; i < l; i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
};
return returns;
};
if(style = dom.currentStyle){
for(var prop in style){
returns[prop] = style[prop];
};
return returns;
};
return this.css();
}
})(jQuery);
Basic usage is pretty simple, but he's written a function for that as well:
$.fn.copyCSS = function(source){
  var styles = $(source).getStyleObject();
  this.css(styles);
}
Why not use .style of the DOM element? It's an object which contains members such as width and backgroundColor.
I had tried many different solutions. This was the only one that worked for me in that it was able to pick up on styles applied at class level and at style as directly attributed on the element. So a font set at css file level and one as a style attribute; it returned the correct font.
It is simple! (Sorry, can't find where I originally found it)
//-- html object
var element = htmlObject; //e.g document.getElementById
//-- or jquery object
var element = htmlObject[0]; //e.g $(selector)
var stylearray = document.defaultView.getComputedStyle(element, null);
var font = stylearray["font-family"]
Alternatively you can list all the style by cycling through the array
for (var key in stylearray) {
console.log(key + ': ' + stylearray[key];
}
#marknadal's solution wasn't grabbing hyphenated properties for me (e.g. max-width), but changing the first for loop in css2json() made it work, and I suspect performs fewer iterations:
for (var i = 0; i < css.length; i += 1) {
s[css[i]] = css.getPropertyValue(css[i]);
}
Loops via length rather than in, retrieves via getPropertyValue() rather than toLowerCase().

Categories

Resources