I'm trying to change the style of all links in a page via Javascript.
I tried both these but no success:
document.links.style.cursor = "wait";
document.getElementsByTagName(a).style.cursor = "wait";
What am I doing wrong?
var allLinks = document.links || document.getElementsByTagName('a');
for(var n=0;n<allLinks ;n++)
document.allLinks [n].style.cursor = "wait";
The document.links is an array of elements, so document.links.style.cursor = "wait" equals to [link1,link2].links.style.cursor = "wait".
And about document.getElementsByTagName(a): the syntax is wrong, you forgot the quotes. The correct is document.getElementsByTagName("a")
var style = document.createElement("style");
document.head.appendChild(style);
try {
style.innerHTML = "a { cursor: wait; }";
}
catch (_ie) {
style.styleSheet.cssText = "a { cursor: wait; }";
}
Of course alternatively you could plan in advance for the eventuality of needing your links to change, and pre-load a static style sheet like this:
.wait-links a { cursor: wait; }
Then whenever you add the class "wait-links" to the <body> (or any container you like), the <a> tags will all be affected. That'd be much more efficient than iterating over the elements changing their individual styles (probably), though if there aren't many links it probably doesn't matter.
Using a style sheet for such things is, in my opinion, a much better practice. In this case, in fact, it'd be better not to call the class "wait-links", but rather use some word or words that describe what's actually happening. Then your JavaScript code just establishes the situation by adding (or removing) the class, and the style sheet controls the appearance changes. If you decide that in some cases the situation calls for the links to change color or become invisible, you can do that without having to root around in your scripts looking for style changes.
Using the JQuery and the ".css" method removes the need to have a for loop and simplifies the code.
$('a').css("cursor","wait");
Related
I know how to use JS to add a stylesheet to an HTML document:
// given CSS as text, add a <style> to the document
function addStyle(css) {
var style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
}
How do I create a checkbox that can toggle this (and only this) stylesheet on and off?
This answer gives hints about how to manipulate stylesheets in JS, but there does not appear to be a way of locating a specific stylesheet without looping through document.styleSheets and matching against document.styleSheets[i].cssRules[j].cssText, which seems unwieldy.
Is there a better way to do this, ideally without jQuery, than a double loop?
(My particular use case is for a userscript (e.g. Greasemonkey), though I avoid GM_addStyle for portability. All this really means is that I don't have direct control over the HTML; I'm modifying other sites.)
In writing this question, I figured out the answer, though it still leaves open the question of how to manipulate preexisting stylesheets without too many loops.
Basically, while I can't use getElementById() or querySelector() to find a style element by its id attribute (because it's not in the body), I can save the object itself when I create it:
// given CSS as text, add a <style> to the document and return it
function addStyle(css) {
var style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
return style;
}
var toggler = addStyle(`
tr.informational { display:none; }
`);
// create and insert the toggling checkbox
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = true;
checkbox.onchange = function() { toggler.disabled = ! toggler.disabled };
var label = document.createElement("label"); // <label> allows clicking on text
label.appendChild(checkbox);
label.appendChild(document.createTextNode("Hide informational rows"));
document.getElementById("buttons").appendChild(label); // add to button panel
I had previously thought that Greasemonkey's security prevented accessing its objects after it finishes loading. This would have meant the checkbox.onchange() line wouldn't work. My original code was therefore quite ugly, finding toggler_index by looping over document.styleSheets[] to find my CSS and then constructing independent JS within JS by hard-coding that index:
checkbox.setAttribute("onchange", `
var toggler = document.styleSheets[${toggler_index}];
toggler.disabled = ! toggler.disabled;
`);
Thanks to StackOverflow for forcing me to question my assumptions when simplifying my question for posting here!
In Wordpress, <img> is inside <a> tag like below.
<a>link text</a>
<a><img src="#"></a>
I added style of dotted border to the bottom of <a>, but there's also dotted border under every picture I post.
So I tried to add a function in function.php, in order to remove border of <a><img src="#"></a>, but it failed. Please help me with code below.
function removeAnchorBorder() {
var anchorWithPic = document.getElementsByTagName("a");
if (anchorWithPic.contains(img) = true) {
anchorWithPic.style.border = "none";
}
add_filter("the_content", "removeAnchorBorder");
Since CSS doesn't have look-ahead, you can't override it with plain CSS and must resort to using JavaScript.
This is a very naive approach, with much logic that could be optimized or abstracted to use jQuery if you prefer:
var withoutImg = Array.prototype.slice.call(document.querySelectorAll('a'),0);
var withImg = Array.prototype.slice.call(document.querySelectorAll('a img'),0);
withoutImg.forEach(function(node){
node.style.borderStyle = "dotted";
});
withImg.forEach(function(node){
node.parentElement.style.borderStyle = "none";
});
Here is a visual example.
Also note that .forEach() may not be available in all browsers, and the Array slice reference is just a trick to convert the selected NodeList into actual iterable arrays.
I have been long battling this, and I would like to know if any others have feedback. I am about to make a customized library for building web apps quickly, and I want to make sure I use the right approach. I WANT to use this method:
$.fn.someSlider = function(){
var coreStyle = '.slider ul { white-space: nowrap; } .slider ul li {display: inline-block}', coreStyleTemplate = '<style><\/style>';
}
But I feel like hard coding the base CSS into the widget is always frowned upon - instead I see SO users recommending the use of CSS style rules instead of this option. I really really really want that 'it just works' feel, and having to force my users to use a separate style sheet just to get my plugins working... well is annoying!
Just to clarify: I would like to include all base style rules needed for the widgets proper/base functionality to be included inside the script. The user would easily modify the base look of the widget by writing a style rule in their own style sheet.
Example:
Instead of having to look through all the base styles trying to find the font color like this... .slider {display: inline-block; color: #000; someotherconfusingrule : blahblah; }
The user simply starts a new rule with the classes name/selector being used - and then just write the changes to make to the default script styles
They would just write
.slider {color: #000};
Thanks for the help in advance SO!
Nice question! Although I'm not sure what the preferred solution to this would be, I was thinking of the following approach:
Use a IIFE to define your jQuery plugin and enable you to define some private, global variables and functions.
$.fn.pluginName = (function() {
return function() {
...your regular plugins code...
};
}();
Define your plugins CSS as a list of style rules in your plugins code
var rules = [
'.box {' +
' width: 100px;' +
' background-color: #f99;' +
' margin: 10px;' +
' padding: 10px;' +
' font-family: Helvetica, Arial;' +
' text-align: center;' +
'}'
];
Create a private variable that remembers if your stylesheet has already been added to the document
var styleSheetExists = false;
Create a private function that creates a stylesheet using the style rules above and that adds it as the first <style> element in the <head> allowing the user to override styles in their own CSS. See http://davidwalsh.name/add-rules-stylesheets for a good tutorial on how to do this properly
var createStyleSheet = function() {
var style = document.createElement("style");
style.appendChild(document.createTextNode(""));
$('head').prepend(style);
for (var i = 0; i < rules.length; i++) {
style.sheet.insertRule(rules[i], i);
}
};
The first time your plugin is applied to an element check if the stylesheet has already been created and if not create the stylesheet.
var $elements = $(this);
if (!styleSheetExists) {
createStyleSheet();
styleSheetExists = true;
}
$elements.each(function() {
$(this).addClass('box');
});
return $elements;
See http://codepen.io/ckuijjer/pen/FkgsJ for this example. It creates a jQuery plugin called box which simply adds the class box to an element. The class box has a default pink background color defined in its stylesheet which gets overridden by a user defined blue background color.
But please do make this configurable in your jQuery plugin. You want to enable developers to bundle all their css, including your plugins, to optimize resource delivery to the client. Plus injecting stylesheets might be a small performance hit.
It may seem annoying but separating the model, view, and controller is the correct way. You're using jQuery so why not consider how jQuery would approach the situation: a jQuery UI widget like the Accordion comes with several stylesheets, the most important being the base stylesheet and a separate 'theme' stylesheet that (if done correctly) is nondestructive and can be modified without risking the integrity of the widget. You may also want to consider how your favorite plugins are authored and what makes them appeal to you. It's my personal opinion CSS should never be present in JavaScript files however if you've made up your mind, the solution #ckuijjer provided is sound. Hope this helps!
This question already has answers here:
Overriding !important style
(11 answers)
Closed 1 year ago.
I tried to inject a style using this code:
document.body.style.color='green!important';
Per the CSS cascade ref, by applying the !important rule I can trump origin and specificity.
I tried to inject this using Firefox Firebug into www.google.com however no luck.
How do I inject a foreground color with an !important rule?
Per the spec, if you want to set the priority, not just the value, you have to use setProperty, like so:
document.body.style.setProperty ("color", "green", "important");
element.style.cssText = 'color:green !important';
should work for you.
style.cssText is the only way to add !important.
<script>
document.body.style.cssText='color: red !important;'
</script>
all answers are great but they all assumed the value of the attribute is fixed,, what if not
take look at my solution
this.style.setProperty("color", $(this).css('color'), "important");
instead of hand writing the value, I got it using jquery $(this).css('attr')
I would like to pose that it may not be working not so much due to any error in code (excepting the space) but more because modifying the body tag isn't a specific enough element, class, or what have you to create the desired effect.
Like for instance the page text of a search result has a class of "st".
all search results are each encapsulated in an
<li>
tag.
So some code to such effect might look like this:
var arr = document.getElementsByClassName('st');
for(i=0; i<arr.length; i++){
arr[i].style.color="green";
}
Use only this:
document.body.style.color="green";
you can not have to use important in this way. Anyway as Fatal pointed out, this will not work, when there is directly important rule in css stylesheet, that you need to override.
In that way, you have to dynamicaly create stylesheet and ad it inside head:
function addNewStyle(newStyle) {
var styleElement = document.getElementById('styles_js');
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = 'styles_js';
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
styleElement.appendChild(document.createTextNode(newStyle));
}
Then you can update style just like that
addNewStyle('body {color:green !important;}')
i need to keep !important for the following code how to do
<script> var size = $(window).width();
if(size >="1900" && size <="2890"){
$(document).ready(function(){ $(".myMove").click(function(){ $(".hqnblogo").animate({ left:'-22% ', top: '67%', height:'7%', }); $(".hqnbnaturalslogo").animate({ left: '86%', top: '20px', height:'7%', }); }); }); } </script>?
HI,
I'm trying to develop some code in Javascript that adds highlighted text to a class. What I want to achieve with this is the ability of text highlighting with a custom color.
I want it to kind of look like the following:
window.getSelected = "<span class=\"highlighted\">" + window.getSelected + "</span>"
after the above code is executed the selected text's background is surrounded by span tags.
thanks,
fbr
You'll want to look into Range Objects, there is a good summary here:
http://www.quirksmode.org/dom/range_intro.html
Browser compatibility will be an issue, but basically, you can get the current selection in the way you suggest, then convert it into a Range, and use the methods of the Range object to find and split the existing DOM nodes, and insert your own <span> tag containing the selected text.
It's not entirely trivial, and involves getting into serious DOM manipulation, but it's a rewarding subject to get your head around. Enjoy!
If you are talking about styling native selections, use ::selection and ::-moz-selection in CSS.
::selection {
color: ...;
background-color: ...;
}
::-moz-selection {
color: ...;
background-color: ...;
}
Alternatively, if you want to highlight an arbitrary element with a class:
CSS
.highlighted {
color: ...;
background-color: ...;
}
JavaScript
yourElement.className = "highlighted";
excuse my english, do you mean adding a class to a text?
function changeClass (elementID, newClass) {
var element = document.getElementById(elementID);
element.setAttribute("class", newClass); // This is for good browsers
element.setAttribute("className", newClass); //For IE<
}
leave all lines, its harmless if you do that way.
If you are using the jQuery framework you can try with the following code:
var your_color = 'yellow';
$('.your-class').css('background-color', your_color);
If you're not using it I highly suggest you start; it makes things a lot easier, it's very stable and it's used by many popular websites including google and stack overflow itself.