Styling a div's links in Javascript [duplicate] - javascript

This question already has answers here:
Setting CSS pseudo-class rules from JavaScript
(12 answers)
Closed 9 years ago.
I would like to change the style of an element's links using JavaScript. The CSS would look like:
#element a:link {
color: #000;
}
I know that you can change the style of the the element itself, as in:
elementObject.style.color = '#000';
Pseudo-code for what I want would be:
|
V
elementObject.[A:LINK].style.color = "#ff0000";
How can I do this?

the :link :visited are not true CSS elements, but part of the CSS rule, this means you need to edit the rule, change the rule or apply another class...
var css='#element a:link { color: #ff0000 }';
style=document.createElement('style');
if (style.styleSheet)
style.styleSheet.cssText=css;
else
style.appendChild(document.createTextNode(css));
document.getElementsByTagName('head')[0].appendChild(style);

You can loop through links and set the one by one.
<script type='text/javascript'>
function new_window()
{
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++)
{
anchors[i].style.color = '#000';
}
}
window.onload = new_window;
</script>
The other way to create a wrapper div with the "wrapper" class name. Then replace its class name to "wrapper2" with JavaScript. After then the rules in the CSS like .wrapper a will be activated.
.wrapper a
{
//normal code
}
.wrapper2 a
{
color: #000;
}

select visited links is javascript isnt possible merely by a selector. have a look at Detect Visited Link In Chrome
and this http://archive.plugins.jquery.com/project/Visited
so if you wanna set the style of a visited/unvisited link using javascript loop through all the links in the body. checking wether they are visited and then apply style.
var as = document.getElementsByTagName('a');
for(var i=0;i<as.length;i++){
//check and set the style here
}

function addCss(sel, css){
S= document.styleSheets[document.styleSheets.length-1];
var r= (S.cssRules!= undefined)? S.cssRules: S.rules;
if(S.insertRule) S.insertRule(sel+'{'+css+'}',r.length);
else if(S.addRule)S.addRule(sel,css,r.length);
}
addCss('button:hover','background-color:blue;');

Related

How to select a particular element in DOM and not its parent element using js

I am trying to create a chrome extension, which can be used to inspect elements on any webpage. It should have two functionalities -
On clicking, it should return the html markup and css styles of
that particular element.
On hover, it should highlight the particular element (just like
inspector in chrome dev tools)
I have achieved first part, but i am not able to achieve the second part.
I am new to JS and trying to achieve the hover task using plain JS, without any jQuery.
This is my content script file
console.log("Chrome extension loaded");
var all = document.body.getElementsByTagName('*');
var divs = document.body.getElementsByTagName('*');
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.h:hover { background-color: #83aff7; }';
document.getElementsByTagName('head')[0].appendChild(style);
// for click events and functionality
for (var i = 0, max = all.length; i < max; i++)
{
all[i].addEventListener("click",function() {
console.log(this);
console.log(window.getComputedStyle(this));
});
}
// for hover event
for (var i = 0, ma=divs.length; i <ma; i++)
{
(divs[i]).addEventListener('mouseover', function(){
this.classList.add('h');
});
if(this.parentNode && this.parentNode.hasAttribute("class"))
{
divs[i].addEventListener('mouseover', function(){
this.parentNode.classList.removeClass('h');
});
}
The clicking events part is working fine but in hover event, the color of parent as well as the element changes. Only the color of particular hovered element should change.
Thanks in advance!
You can use "addEventListener" to achieve "mouseover" to the element
You need to edit your css style
style.innerHTML = '.h:hover { background-color: #83aff7; }';
This says if an element with class h is being hovered, set background color. You are adding the "h" class to the parent with
$(this).parent().addClass('h');
CSS RULE 1 (if parent is of class h AND parent is hovered, color background):
style.innerHTML = '.h:hover *{ background-color: #83aff7; }';
CSS RULE 2 (if parent is of class h AND element is hovered):
style.innerHTML = '.h *:hover{ background-color: #83aff7; }';
Make sure to pick the rule that is appropriate for you.
Working JS Fiddle with both examples (your original CSS is the third box): https://jsfiddle.net/nsevpqd9/
If you do not want to edit your CSS style at all then add the class to the element itself, not the parent:
$(this).addClass('h');

Modify previously defined style in JS

A function for creating style constructed as follows
function createStyle(css) {
var head = document.head || document.getElementsByTagName("head")[0];
var style = document.createElement("style");
style.type = "text/css";
if(style.styleSheet) {
style.styleSheet.cssText = css;
} else {
var textNode = document.createTextNode(css);
style.append(textNode);
}
head.append(style);
}
inspired by Christoph and TomFuertes code. Then it is called to create a style with class name tab
createStyle(`
.tab button {
background: inherit;
float: left;
outline: none;
border: none;
padding: 8px 6px;
width: 60px;
cursor: pointer;
}
`);
and a HTML element using the style
var div = document.createElement("div");
div.className = "tab";
parent.append(div);
is also created. So it all works.
After that I need to modify the style with class name tab, where following code
var style = document.getElementsByTagName("style");
var css = style[0].innerHTML
var className = css.split(" ")[0].split(".")[1];
is used to get the style class name. I have managed to get the style class name tab and also the string containing the object in css.
The question is how I modify the style without I modify the string and recreate the style? Or if I have to do that, how I should delete the previous defined style if there are already some styles which I have not recorded the order for accessing them through array sytle[].
Proposed solution
Using How to change/remove CSS classes definitions at runtime? suggested by Achu I made this function
// Change style attribute with value
function changeStyleAttribute(style, attr, value) {
var N = document.styleSheets.length;
var styles = document.styleSheets;
for(var i = 0; i < N; i++)
{
if(styles[i].rules[0].selectorText == style)
styles[i].rules[0].style[attr] = value;
}
}
which is called
changeStyleAttribute(".tab", "width", "299px");
and works. I hope there is another better and simpler solution.
You'll want to use document.styleSheets[i].cssRules which is an array you need to parse through to find the one you want, and then rule.style.setProperty('font-size','10px',null);
Refer to this link: How to change/remove CSS classes definitions at runtime?.
Hope this helps.

CSS selector for ALL elements with SAME CLASS after and before current element

I was looking here: CSS Selector for selecting an element that comes BEFORE another element?
...but wasn't able to find a correct answer for my issue.
Here is a fiddle example: https://jsfiddle.net/Munja/bm576q6j/3/
.test:hover, .test:hover + .test
With this, when I :hover element with .test class, I achieved to change style for current element with .test class and first next element with .test class.
What am I trying to achieve?
When I select any row/column (e.g agent 2), I want to apply same style for ALL elements with that same class (.test in this case).
If it is not possible to achieve this with css only, * I am willing to accept and other good solution.*
Thank you.
In your specific case you can use
tbody:hover > .test {
background: green;
}
fiddle: https://jsfiddle.net/bm576q6j/4/
Note that if you add more classes in the same tbody it will not give what you want. Check also this question: Hover on element and highlight all elements with the same class
So, after waiting for several more hours, I have decided to use JavaScript solution mentioned in answer from #BasvanStein. Posting it here as answer, to make things easier for someone else with same issue.
Here is a working fiddle: https://jsfiddle.net/Munja/bm576q6j/15/
var elms = document.getElementsByClassName("test");
var n = elms.length;
function changeColor(color) {
for(var i = 0; i < n; i ++) {
elms[i].style.backgroundColor = color;
}
}
for(var i = 0; i < n; i ++) {
elms[i].onmouseover = function() {
changeColor("red");
};
elms[i].onmouseout = function() {
changeColor("white");
};
}

How to get a style property from a css class and set it to another css class?

Is it somehow possible to get a style property from a css class that is not used anywhere?
I'd like to read for example the color property that I want to apply to an animation with jquery ui but I want to avoid duplicating them again in the js code.
Let's say I have this:
.default-style {
color: red;
}
.disabled-style {
color: gray;
}
.current-style {}
<span class="current-style">Hello world!</span>
Now I would like to set the .default-style color to the .current-style and then animate the color from the .default-style to the .disabled-style and back on click but I don't know how to get them without creating a hidden element.
var currentColor = ""; // I'm stuck here. Get color from css class?
$("span.abc").animate({ color: currentColor });
You can cheat by creating an element, applying the class, adding the element to the document, getting its color, then removing it. If this is all done in one code block, the user will never see the element:
var div = $("<div>").addClass("default-style").appendTo(document.body);
var color = div.css("color");
div.remove();
Alternately, you can loop through document.styleSheets in the document, and loop through the rules of each stylesheet looking for the one that uses that simple class selector, then look at the styles that rule defines.
Gratuitous snippet: ;-)
var div = $("<div>").addClass("default-style").appendTo(document.body);
var color = div.css("color");
div.remove();
$("<p>The color is: " + color + " (the color of this paragraph)</p>").css("color", color).appendTo(document.body);
.default-style {
color: red;
}
.disabled-style {
color: gray;
}
.current-style {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="current-style">Hello world!</span>
Side note: jQuery's animate function doesn't animate colors natively, you need to add a plugin to do it (jQuery UI bundles one, but if you're not using jQuery UI, you can just use one of the plugins that does this, such as this one, directly).
Correct Way ! Without cheating the document
var currentColor;
var styleSheets = document.styleSheets;
for(var j=0; !currentColor && j<styleSheets.length; j++)
{
var styleSheet = styleSheets[j];
var cssprops = styleSheet.cssRules || styleSheet.rules; // .rules is for older IE
for (var i = 0; i < cssprops.length; i++) {
if(cssprops[i].selectorText == '.default-style');
currentColor = cssprops[i].style.getPropertyCSSValue('color').cssText;
}
}
$("span.abc").animate({ color: currentColor });
Reference From https://developer.mozilla.org/en-US/docs/Web/API/document.styleSheets

how can I detect the css value with jquery? [duplicate]

This question already has answers here:
Can jQuery get all CSS styles associated with an element?
(5 answers)
Closed 8 years ago.
Suppose in my style sheet:
.test{width: 20px; height: 50px; color: blue;}
.some-test{padding: 20px; margin: 10px;}
.even-test{font-size: 20px; color: red;}
Is it possible to detect the 20px value of each css properties so that I could replace it?
I'm supposing to detect something like this:
$('.selector').filter(function() {
return $(this).css(property) === '20px';
}).css(property, value);
Isn't there anything something like: style.arguments[] ?
You can use the filter function in jQuery to find all elements that have that width.
$('.allYourSelectors').filter(function() {
return $(this).css('width') === '20px';
}).css("width", newWidth);
However, it would be much better to just give them all the same class that you can modify.
To search through CSS styles (not sure if this gets style="..." styles):
var parseStyle = function(rules) {
for (var i = 0; i < rules.length; ++i)
{
console.log(rules[i].style.width);
}
};
//care needs to be taken as to when this executes - styles may not have been loaded yet
for (var i = 0; i < document.styleSheets.length; ++i)
if (document.styleSheets[i].rules && document.styleSheets[i].rules.length > 0)
parseStyle(document.styleSheets[i].rules);
If it's not the CSS properties you want but the result of the style on an element, this might be more what you're after...
var element = ... jquery or whatever
var elementStyle = element.currentStyle || getComputedStyle(element);
console.log(elementStyle.width);

Categories