Override existing style declaration with jQuery - javascript

I have the following HTML code:
<style>
.thing { color: red }
</style>
<p class="thing">This is a nice thing</p>
I would like to change the ".thing"-style for all current content and all future content which comes to the page via AJAX.
$('.thing').css('color', 'blue');
This would work, but if new HTML code is added to the document via AJAX, all ".thing"-elements will still be colored red.
What I want is to change the whole style property ".thing" for the document and not only for the current elements (with a jQuery selector).
Thanks!

You could add a style rule in the header with the DOM
Demo: The Problem
Demo: DOM Mutation Solution
var newStyles = document.createElement("style");
newStyles.type="text/css";
newStyles.innerHTML = ".thing{color:blue}";
document.head.appendChild(newStyles);

You could use a call back function on your AJAX code to run the jquery css function.
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$('.thing').css('color', 'blue');
}
});

If for some reason you are not able to use any of the techniques given in the duplicate question, you could modify the stylesheet itself, for example:
document.styleSheets[1].cssRules[0].style.color = "blue";
However, the above line is not cross browser (I don't think it will work in IE, which prefers rules instead of cssRules) but it's possible to make it cross-browser compatible with a bit more code.
All it does is change the actual stylesheet, so it's like you had color: blue in there all along. This will affect elements currently on the page, and any that are added in the future (see the fiddle for a working example).
Note that you'll have to modify the indexes to suit your page. The indexes used in the example are just what work for the given stylesheet on jsfiddle.net.
Edit an attempt at a cross-browser solution:
var cssRules = (document.styleSheets[1].cssRules) ? document.styleSheets[1].cssRules[0] : document.styleSheets[1].rules[0];
cssRules.style.color = "blue";

You could add a style rule for blue text
<style>
.thing { color: red }
.thing.blue { color: blue }
</style>
and add "blue" class via call back function on your AJAX
$('.thing').addClass('blue');

Related

Copying style from querySelector

I'm trying to copy a style from the .current_page_item to different elements.
I am using WordPress and am not sure of another way to do this dynamically.
Essentially, I am using one style to color the .current_page_item (which changes colors depending on which page), and that is modifying the header color, and the post and content background colors.
The way I have thought up to do this is via JavaScript.
Here is my code:
window.onload = function() {
var page_color = document.querySelector('li.current_page_item').style.backgroundColor;
document.querySelector('div.blog-post p').style.backgroundColor = page_color;
document.querySelector('h2.blog-post-title').style.backgroundColor = page_color;
}
It doesn't seem to be reading the backgroundColor from .current_page_item, but I am able to set it if I use the same method.
Here is the page: http://whatloop.com/wpTheme/
Thanks!

How can I change css for every DOM object in the page in SAPUI5

I have a things inspector and this things inspector has two titles. I wan to be able to change the css on this titles and make their font size a bit smaller( default fontSize is 16px and I want to drop it to 12px). I tried to get these titles class and use this method to change their size:
var element = document
.getElementsByClassName("sapUiUx3TVTitleSecond")[1];
element.style.fontSize = '12px';
var element = document
.getElementsByClassName("sapUiUx3TVTitleFirst")[1];
element.style.fontSize = '12px';
it does work and I can see the change but as soon as the page finishes loading ( page loading takes couple of second because it needs to read a json object) title sizes go back to its default.
I dont even know this is a right way to access DOM elements and change their CSS.
Please point me to the right direction of how to change DOM object css in SAPUI5 in general
You could create a new CSS file which you include in your index.html.
Just add the needed selectors with the modified attributes in this custom CSS:
.sapUiUx3TVTitleSecond, .sapUiUx3TVTitleFirst {
font-size : 12px;
}
Edit: if you need to change it programmatically, you could use the addStyleClass("yourStyle") method which is available to every UI element
Execute the script after dom gets completely loaded. Try like this
$("document").ready(function()
{
var element = document
.getElementsByClassName("sapUiUx3TVTitleSecond")[1];
element.style.fontSize = '12px';
var element = document
.getElementsByClassName("sapUiUx3TVTitleFirst")[1];
element.style.fontSize = '12px';
})
$("document").ready(function()
{
$(".sapUiUx3TVTitleSecond").css("font-size","12px");
})

Is it possible to calculate (compute) resulting css style manually?

Is it possible to compute resulting css style on the element manually (without need to render it)?
Lets say I'm supposed to have an HTML structure:
<p style="some_style1">
<span style="some_style2">
<span style="some_style3">
TEXT
</span>
</span>
</p>
I know what are some_style1, some_style2, some_style3 in terms of JS object (for example i have data for each element like: {font: 'Times New Roman' 12px bold; text-align: center;})
I want to MANUALLY (without need to render in browser the whole structure) compute resulting style that will effect "TEXT".
What algorithm (or solution) should I use?
There exist browsers that don't need rendering in a window (headless browser). You can load a page and query what you want. It won't be easier than in a normal browser to obtain what you ask though.
JSCSSP is a CSS parser written in cross-browser JavaScript that could be a first step to achieve what you want from scratch or quite. Give it a stylesheet and it'll tell you what a browser would've parsed. You still must manage:
the DOM,
inheritance of styles,
determine which rules apply to a given element with or without class, id, attributes, siblings, etc
priorities of selectors
etc
Its author is D. Glazman, co-chairman of the W3C CSS group and developer of Kompozer, NVu and BlueGriffon so it should parse CSS as expected :)
The simplest thing I can think of is to wrap the whole thing in a a container that you set display: none on, and append it to the DOM. The browser won't render it, but you'll then be able to query the computed style.
Here's an example showing how jQuery can't find the style information when the structure isn't connected to the DOM, but when it is, it can:
jQuery(function($) {
// Disconnected structure
var x = $("<p style='color: red'><span style='padding: 2em'><span style='background-color: white'>TEXT</span></span></p>");
// Get the span
var y = x.find("span span");
// Show its computed color; will be blank
display("y.css('color'): " + y.css('color'));
// Create a hidden div and append the structure
var d = $("<div>");
d.hide();
d.append(x);
d.appendTo(document.body);
// Show the computed color now; show red
display("y.css('color'): " + y.css('color'));
// Detach it again
d.detach();
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
});
Live copy | source
I can't guarantee all values will be exactly right, you'll have to try it and see; browsers may defer calculating some things until/unless the container is visible. If you find that some properties you want aren't calculated yet, you may have to make the div visible, but off-page (position: absolute; left: -10000px);
I found some articles about this: Can jQuery get all styles applied to an element on Stackoverflow.
Also this one on quirksmode: Get Styles that shows the following function:
function getStyle(el,styleProp)
{
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
This allows you to query for style properties
Styles override each other in the order in which they're defined: So anything in some_style3 that overrides the same selector in some_style2, say, will do. Otherwise, it will just be a union of the sets of selectors.
EDIT Some selectors won't override, but instead act relatively on a previous definition, so you've got to be careful about that.

jQuery and selectors in use with specific span tags

jQuery selector
Selecting specific span tags
I had this problem with jQuery's selector. It was a problem for hours. It could not select that specific span tag that I wanted to manipulate and that's why I'm stuck scratching my head with this one.
My goal was to add different classes for each span tag that had different style values.
Thus I almost succeeded I couldn't figure out how to add different classes to each span tag, so I ended up clueless.
I basically want the span with font-size of 180% to be in a specific class doesn't matter which really cause I can change that later if the code works. The other span tag with font-size of 100% should also have a class, the other class. I hope you get more clarity in what I'm trying to do now at least that's what I'm hoping for.
The code exists in the link below, feel free to post a fix and optionally but not required a explaination of why it didn't work! thank you.
jQuery Submission: JS Bin Post
Here's the code itself aswell.
var val1 = "font-size: 180%";
var val2 = "font-size: 100%";
var title = $("span").attr("style");
$(function(){
if ($("span:contains('font-size: 100%')")) {
$('span').addClass("text_shadow2");
if ($('span').has("text_shadow1")) {
$('span').removeClass("text_shadow1");
}
}
if ($("span:contains('font-size: 180%')")) {
$('span').addClass("text_shadow1");
if ($('span').has("text_shadow2")) {
$('span').removeClass("text_shadow2");
}
}
},function(){
if ($("span:contains('font-size: 100%')")) {
$('span').addClass("text_shadow2");
if ($('span').has("text_shadow1")) {
$('span').removeClass("text_shadow1");
}
}
if ($("span:contains('font-size: 180%')")) {
$('span').addClass("text_shadow1");
if ($('span').has("text_shadow2")) {
$('span').removeClass("text_shadow2");
}
}
});
if ($(val1==title)) {alert("1. "+title);}
if ($(val2==title)) {alert("2. "+title);}
You could do something like this to parse the style attribute. Browsers aren't going to set the font-size property to a percentage but will do the calcs instead
$('span').filter(function(){
return $(this).attr('style').match('180%');
}).addClass('someClass');
Demo: http://jsfiddle.net/AbZBD/

Can't change background of div region using javascript?

This should be so simple, but I'm making heavy weather of it.
Div region set out as:
<div class="maincontent">
Stuff in my div
</div>
CSS for that div:
.maincontent{
height: 100%;
background-size: 100%;
margin-left:1%;
margin-right:1%;
font-size:16px;
}
Then I have:
onLoad=changeBackground();
But before that I have the function:
function changeBackground(){
document.getElementByAnything('maincontent').style.backgroundColor="yellow";
}
I know its making the call to the function because if I put an alert box in there that shows. But no matter what combination of getElementBy I can't make any changes to the background?
Please help as its driving me insane!
TIA
Have you tried giving your div an id and using document.getElementById('divId') instead? I think if you want to get the element by class you have to use jquery.
getElementById('maincontent')
and change your div to have an id="maincontent"
Try giving the element an id and doing document.getElementById and then do console.log in firebug or other developer tools and verify that you are actually getting a dom element back.
Once you have verified that you should then be able to switch the background color
You're trying to select the div using its class. This isn't quite as straightforward as getting it by id. Try this:
<div class="maincontent" id='mainContent'>
Stuff in my div
</div>
function changeBackground(){
document.getElementById('mainContent').style.backgroundColor="yellow";
}
You can see a working example here: JSFiddle
If you want to get the element using its class, I would recommend using Jquery or another library.
If you're using in line Javascript then use, instead:
onchange="changeBackground(this)"
And:
function changeBackground(elem){
elem.style.backgroundColor = "yellow";
}
Edited as I suddenly remembered you were discussing events based on div elements. As a div doesn't natively support the onchange event, I'd suggest amending your code to the following (though changing the event-type onmouseover to whatever event you find most appropriate):
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
};
JS Fiddle demo.
Also, to remove the events from in-line code, and to make the JavaScript more portable and less 'intrusive':
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
}
var maincontents = document.getElementsByClassName('maincontent');
for (var i=0,len=maincontents.length; i<len; i++){
maincontents[i].onmouseover = function(){
changeBackground(this);
}
}
JS Fiddle demo.
Bear in mind, though, that some browsers (such as Internet Explorer 8 and below) don't support getElementsByClassName().
I recommend using jQuery if you want to select a DOM by class name.
Put this code in your <head> part of your html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
and change your function to
function changeBackground() {
$(".maincontent").css("background-color","yellow");
}

Categories

Resources