I would ask how to change src of CSS using pure Javascript. I saw on internet that one guy used cookies for this, by i tried sth like this:
window.onload = function onload() {
setTimeout(function(){
document.styleSheets[1].href = "file:///C:/Users/Ma%C5%9Blan/Desktop/Site/bootstrap-3.3.6-dist/project1a.css";
}, 3000);
};
And it didn't work (i want to change CSS after 3 s, i know that actual localization is local, on my PC. Just trying :) ). I want to swap whole file.
Any ideas? If it's impossible in pure JS, show me jQuery way then.
Thanks!
document.styleSheets is a READ-ONLY property, so you won't be able to change the properties of that array.
What you want to do instead is get a list of all the <link> elements in the head, then either use a regex or conditional statement to get the element you are looking to replace, and use .href on that element.
E.G.
// get all links in the head (including CSS)
var allLinks = document.head.getElementsByTagName('link');
// find and replace the element
for (var i = 0; i < allLinks.length; i++) {
if ( allLinks[i].href = "old/url/to/css/file.css") {
allLinks[i].href = "file:///C:/Users/Ma%C5%9Blan/Desktop/Site/bootstrap-3.3.6-dist/project1a.css";
}
}
Related
JavaScript Newbie so the following question maybe 'dumb'.
For my work I do a little GreaseMonkey scripting to make our eCommerce store back end a little more friendly to our customer service team. Normally I'd make a new or better UI for them setup a special role or something, but with this current system, this is literally not an option.
Specifically I make a selection of links visibility: hidden, as they trigger some reporting functions which can lock up the backend till the reports are completed.
Up to this point I have had the script load jQuery, which is fine but not ideal. Then I dug in and saw that the interface was built using YUI, while this is already loaded, the syntax is weird to me, and I don't like it much, plus it is now not supported.
Recently I found the Plain JS site, which describes how to use 'vanilla' JS to do jQuery like things. Splendid! I thought, Now I can just write simple JS without extra dependencies or libs! But this is not quite the case.
I have tried the following:
var links = Array.from(document.querySelectorAll("a")); // creates an actual array from the node list returned by document.query
var links_to_hide = links.slice(14, 22); // gets just the bits we want to affect from the array, and is still an array
// ok so 'links_to_hide' is an array, and it is an array of 'a' anchor tags.
// if I go into the inspector and set the visibility property it affects the tag but doing it via scripting seems to not work.
// so if links_to_hide is an array it should be possible to
for(var i = links_to_hide.length; i <= links_to_hide.length; i++){
links_to_hide.style['visibility'] = 'hidden';
}
// this for loop doesn't seem to actually affect anything
What am I missing. Near as I can tell this should work.
Change this:
for(var i = links_to_hide.length; i <= links_to_hide.length; i++){
links_to_hide.style['visibility'] = 'hidden';
}
To this
for(var i = 0; i < links_to_hide.length; i++){
links_to_hide[i].style['visibility'] = 'hidden';
}
You aren't using i
links_to_hide[i].style.visibility = 'hidden';
Your for loop should be like below:
for(var i = 0; i < links_to_hide.length; i++){
links_to_hide[i].style.visibility = 'hidden';
}
Is there a way to set css :focus using JS to all document without running a script for checking every element? Something like this, perhaps:
document.style.focus.backgroundColor = "#FF0000"; ?
I know this won't work, but is there any way to do something similar to this? If not, then how should I set the :focus globally for some specific style?
The only way I got is to run for all elements and only then attach styles for them, like this:
function TheFunction() {
var findthemall = document.querySelectorAll("*");
var i;
for (i = 0; i < findthemall.length; i++) {
findthemall[i].style.backgroundColor = "red";
//etc, etc, etc...
}
}
But I think it's a bad idea
Suppose I have a web page
http://foo.com/bar.html
Is there any way I can provide a link to that page that, for sake of example, makes all <b> sections red?
I'm guessing I need some script in bar.html and a URL something like
http://foo.com/bar.html?style="b{color:red;}"
Is this possible and if so, is there a standard way to do it?
You can read the query string via location.search and then apply whatever logic you want to the string you get back.
Be careful not to open yourself up to an XSS attack.
why don't you try it with CSS?
inside example.css file:
br
{
color:red;
}
I would say the easiest and most abstract way would just be to append the style directly to the head. Again though, as stated, you may want to parse it and verify its proper format and avoid attacks. You'd be giving every web user direct access to your stylesheet in your head.
window.onload = function() {
if(document.location.search.indexOf('style=')>-1) {
var style = decodeURI(document.location.search.substring(document.location.search.indexOf('style=') + 6));
if(style.indexOf(',')>-1) { style = style.substring(0,style.indexOf(',')); }
var elem = document.createElement('style');
elem.type='text/css';
elem.innerHTML = style;
document.head.appendChild(elem);
}
};
Then you could add any and all style modifications to your URI like this ?style=body{background-color:blue;}%20b{color:red;}
You can customize javascript to do whatever you want. There's no pre-existing, universal way of doing this.
You could check document.location.hash to pull out a value and add a new style for b elements. Query-string parsing is a bit more difficult as it's not built into JS by default.
You could add a handler to a link element.
You can do it like this:
document.getElementById('clickme').onclick = function(){
var bolds = document.body.getElementsByTagName("b");
for(var i = 0; i < bolds.length; i++){
bolds[i].style.backgroundColor = 'red';
}
}
Demo: http://jsfiddle.net/maniator/HH2Cv/
I have a video page that has filters for the videos. If I click on one of the filters (e.g. "music videos"), the url changes to something like this:
http://mysite.com/videos/?videofilter=music-videos
Unfortunately, there isn't a body class added or anything where I can easily target it by doing something like this:
body.music-videos { }
Is there a way to somehow target the url using CSS or JavaScript?
You could use Javascript's location.href to get the location, and work with it like a normal string.
But it would be much more recommended to server-side the body to have a class.
Presumably your page loads with that URL - can't you do somehting when you render the page to include something css-detectable?
I don't know if I understand your question. Are you trying to target a link with an href value? You should be able to target that with something like selector[src=URL] in css. If you're trying to target the body tag based on the URL I would create conditional scripts under if statements such as if(location.href=='url'){ document.getElementsByTagName("body").style.property="whatever" } . Hope this helps.
I'm not sure I understand...
So you click the filter options, which sends a query string to the URL. We can get the query string as such:
var qs = [];
var q = window.location.search.substring(1);
var p = q.split('&');
for(var i = 0; i < p.length; i++) {
var pos = p[i].indexOf('=');
if(pos > 0) {
var key = p[i].substring(0, pos);
var val = p[i].substring(pos+1);
qs[key] = val;
}
}
Then you simply access qs['videofilter']to get the value. From there, if it's doing nothing, well – you don't have a filter, you have check boxes. The only way to have a filter is to have some form of commonality by which to categorize them all. If you're wanting to do this through javascript and css, you could use that filter in a regex to find the specific tag whose innerHTML matches the value you got above, then determine the whole container's relationship( e.g. parent, grandparent, etc. ), and set that to display:none;
If you mean something else, please clarify.
This solution is Firefox only unfortunately:
From https://developer.mozilla.org/en/CSS/#-moz-document
#-moz-document url(http://www.w3.org/),
url-prefix(http://www.w3.org/Style/),
domain(mozilla.org)
{
/* CSS rules here apply to:
+ The page "http://www.w3.org/".
+ Any page whose URL begins with "http://www.w3.org/Style/"
+ Any page whose URL's host is "mozilla.org" or ends with
".mozilla.org"
*/
/* make the above-mentioned pages really ugly */
body { color: purple; background: yellow; }
}
How can I remove elements which are created by JavaScript, I tried using CSS by setting display:none; but that doesn't seem to solve my problem, also I can't remove them since I don't have them in HTML, any other ways? Thank you
UPDATE:
Can't use any JavaScript such as jQuery, MooTools, ExtJS etc, and actual elements I want to remove are divs, with a specified class so I can't use getElementById.
I found this script on Google, but it doesn't seem to work but this is what I need:
HERE
This is fairly simple to do this using jQuery.
$("#myId").remove();
will remove
<div id="myId"></div>
Edit: You can also do it with "old school" javascript.
The function you're looking for is removeChild()
Example:
function removeElement(divNum) {
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
You will want something like this to take advantage of browser support where you can:
if(document.getElementsByClassName){
// Safari 3+ and Firefox 3+
var itms = document.getElementsByClassName('your_class');
for(var i = 0; i<itms.length; i++){
var it = itms[i];
if(it.tagName == "DIV"){
it.parentNode.removeChild(it);
i = i - 1; //It actually gets removed from the array, so we need to drop our count
}
}
} else {
// All other browsers
var itms = document.getElementsByTagName('div');
for(var i = 0; i<itms.length; i++){
var it = itms[i];
// Test that className contains your class
if(/your_class/.test(it.className)) it.parentNode.removeChild(it);
}
}
JavaScript handles all memory mangement for you using garbage collection so once all references to an object cease to exist that object will be handled by the browsers specific implementation.
If you have the dom element itself:
if(node && node.parentNode){
// return a ref to the removed child
node.parentNode.removeChild(node);
}
Since you say you can't use Javascript, you're pretty stuck. Have you tried this CSS:
.classname {
display: none !important;
}
It's possible that the created elements have inline styles set on them, in which case normal CSS is overridden. I believe the !important will override inline styles.
Of course, the best solution is not to add the element in the first place... but I'm guessing you're in one of those (unfathomably common) scenarios where you can't change or get rid of the JS?
Not all browsers have a
document.getElementsByClassName
method, but for your purpose you can
fake it well enough- This method does
not work like the native
HTMLElement.getElementsByClassName- it
returns an array, not a live nodelist.
You can specify a parent element and a
tag name to speed it up.
function getElementsByClass(css, pa, tag){
pa= pa || document.body;
tag= tag || '*';
css= RegExp('\\b'+css+'\\b');
var A= [], elements, L, i= 0, tem;
elements= pa.getElementsByTagName(tag);
L= elements.length;
while(i<L){
tem= elements[i++];
if(css.test(tem.className)) A[A.length]= tem;
}
return A;
}
// test
var A= getElementsByClass('removeClass'), who;
while(A.length){
who= A.pop(); // remove from the end first, in case nested items also have the class
if(who.parentNode) who.parentNode.removeChild(who);
who= null;
}
If you have assigned event handlers to
the elements being removed, you should
remove the handlers before the
elements.
You will probably have to be more specific.
The general answer is 'with JavaScript'. As long as you have a way of navigating to the element through the DOM, you can then remove it from the DOM.
It's much easier if you can use a library like jQuery or prototype, but anything you can do with these you can do with JavaScript.
marcgg has assumed that you know the ID of the element: if you don't but can trace it in the DOM structure, you can do something like this (in prototype - don't know jQuery)
var css_selector = 'table#fred tr td span.mydata';
$$(css).invoke('remove');
If you can't use a JS library, you'll have to do the navigation through the DOM yourself, using Element.getElementsByTagName() a lot.
Now you've specified your question a bit: use Element.getElementsByTagName, and loop through them looking at their className property.
Use:
document.removeChild('id_of_element');