change css background of all elements on a page - javascript

I want to change the background image of every element on a page by adding a string to it's address in this manner:
Get the back ground image address of an element from the styles:
background-image: url("img/sprites.png");
Add the string ?ver=3 to it, so it will become like this
background-image: url("img/sprites.png?ver=3");
I guess I may do that on a single known element by somthing like this:
document.getElementById('elementId').style.backgroundImage += "?ver=3"
Am I right?
However, I want to do this to all the elements. How can I have the loop access all the elements?

You could try using jquery.
$("*").css('backgroundImage', $(this).css('backgroundImage')+'?ver=3');
I just typed this from memory so it might not be 100% but it seems like it would work.
Possibly this:
$("*").each(function(){$(this).css('backgroundImage', $(this).css('backgroundImage')+'?ver=3');});
Hope this help a little.

You could use document.getElementsByTagName:
var elms = document.getElementsByTagName('*');
for (var i = 0, len = elms.length; i != len; ++i) {
elms[i].style.backgroundImage += '?ver=3';
}
Or, you could use the DOM to modify the stylesheet object directly. You'd have to write separate codepaths for different browsers, but it would probably run much faster.

maybe something like this with jquery:
$('*').each(function(){
$(this).css( 'background-image', $(this).css('background-image') + "?ver=3");
});
I would prefer to use $('body *') in the selector to not include elements like head and html.

suppose the elements that you want to assign a background to are wrapped in a div with class 'mysprites':
<div id="mysprites">
<div></div>
<div></div>
<div></div>
</div>
To let each sprites.png version number correspond to the i-th element, just call
$('#mysprites').each(function(index) {
$(this).css("background-image", "url(img/sprites.png?ver=" + index + ")");
})
like in this fiddle
(if you don't know jquery, just download it and add it to the header of your html file like:
<script language="javascript" type="text/javascript" src="jquery.js"></script>

Related

jQuery selector is overlooking elements from a separate context

I'm making an ajax request to a page on my site with this element as a direct child of the body tag:
<div class="container" id="wantme"><div class="content"></div></div>
There's only one .container, and I want to grab its ID which I don't know.
As far as I can tell, this code should do what I want:
$.get('/page', function(data) {
id = $('.container', data).attr('id');
});
But the .container selector fails to find anything.
I did find these two workarounds. I can find .content, and I can climb up the tree like this:
id = $('.content', data).parent().attr('id');
But I can't leap directly there.
I found this workaround elsewhere on StackOverflow that works:
html = $('<div></div>').html(data);
id = html.find('.container').attr('id');
But why is it that the seemingly obvious answer doesn't work?
UPDATED ANSWER: I'll leave my original answer at the bottom, however I'm concerned it may misbehave depending on browser. jQuery's .html() makes use of Javascript's innerHTML - some browsers choose to strip <head> and <body> tags when using innerHTML, whereas others do not.
The safest method to achieve what you're after may still be the workaround you mentioned, like so:
var data = '<!doctype html><html><body><div class="container" id="findme"><div class="content"></div></div></body></html>';
var $container = $("<div />").html(data).find(".container");
var id = $container.attr("id");
console.log(id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
More information as to the browser-related issues can be found here.
PREVIOUS ANSWER:
When you pass HTML to a jQuery element, it will ignore the <body> tags, as well as anything outside of them. Given the data string in your JSFiddle, $(data) will create something that looks like this:
<div class="container" id="findme">
<div class="content"></div>
</div>
As you can see in the HTML above, your .container isn't inside of $(data) - it is $(data).
Because $(data) is representing your .container element, you should just be able to do $(data).attr("id") to retrieve what you're after.
var data = '<!doctype html><html><body><div class="container" id="findme"><div class="content"></div></div></body></html>';
var id = $(data).attr('id');
console.log(id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You are not getting the ID from $('.container', data).attr('id'); is because you are setting the value of the second parameter. What you want to do is this: $('.container ' + data).attr('id');.
Update:
If data is a string then you should convert it into a DOM element: $('.container', $(data)).attr('id');

Extract content from <div> tags

I'm wondering how I could 'extract' the content from a set of div tags, for further use (like emailing or displaying elsewhere). The tricky part is that the content in the div's is only made after the page has loaded.
This is the div:
<div class='simpleCart_items'></div>
I have an understanding of javascript and php,
Thanks in advance!
If you use jQuery, very simply:
var content = $('.simpleCart_items').html();
This, assuming you have only 1 element with that classname. Otherwise, you could get other content
Wrap this with the ready() function in jQuery. Please refer to the documentation
You'll have to get the content once it's there, as you can't get something that doesn't exists. With that in mind, you'd get it the same way you would any other content.
var els = document.querySelectorAll('.simpleCart_items'); // nodelist
for (var i=0; i<els.length; i++) {
console.log( els[i].innerHTML )
}

How can i embed a javascript function in css in html?

I have a javascript function named "background_url" that outputs
a random background image.
I'm trying to call the function in this way:
<td style="<script type="text/javascript">background_url();</script>"></td>
but the only thing outputted in my browser is:
a string "background_url();"
The javascript function is as follows
function background_url(){
var myimages=new Array()
myimages[1]="images/img1.jpg"
myimages[2]="images/img2.jpg"
myimages[3]="images/img3.jpg"
//call a random function that returns id of image etc
document.write('background-image: url('+myimages[id]+')');
}
</script>
The background image is not shown,what can i do in order to fix that?
Thanks, in advance
Don't.
Do it the right way.
Give the td element a class (if there are more than one that share the background) or an id (if this element is unique) and use JavaScript to set the style using the appropriate selector.
var tds = document.querySelectorAll('td.some-class-name');
for(var i = 0; i < tds.length; i++){
var td = tds[i];
td.style.backgroundImage = 'url(' + randomImageUrl + ')';
}
Or, if you're using a library like jQuery, it's a little easier:
$('td.some-class-name').css('background-image','url(' + randomImageUrl + ')');
The thing you're running into is that script execution can happen in 2 places: inside a <script> tag (which can't be in an attribute or, as part of an attribute only if it's an event handler. So your choices are:
<script>
background_url()
</script>
Or
<script src="path/to/your/script.js"></script>
Or
<td onmouseover="background_url()">
Given those are your choices, typically people try to use the second option, meaning you'll need to have some mechanism to link your element to the code in question. So you might add an id in your td:
<td id="randomBgElement">
Then onload do this:
document.getElementById('randomBgElement').style = background_url()
Where "background_url()" is a function that returns a valid style, like background-image: url(images/img3.jpg) generated randomly.

.html() and .append() without jQuery

Can anyone tell me how can I use these two functions without using jQuery?
I am using a pre coded application that I cannot use jQuery in, and I need to take HTML from one div, and move it to another using JS.
You can replace
var content = $("#id").html();
with
var content = document.getElementById("id").innerHTML;
and
$("#id").append(element);
with
document.getElementById("id").appendChild(element);
.html(new_html) can be replaced by .innerHTML=new_html
.html() can be replaced by .innerHTML
.append() method has 3 modes:
Appending a jQuery element, which is irrelevant here.
Appending/Moving a dom element.
.append(elem) can be replaced by .appendChild(elem)
Appending an HTML code.
.append(new_html) can be replaced by .innerHTML+=new_html
Examples
var new_html = '<span class="caps">Moshi</span>';
var new_elem = document.createElement('div');
// .html(new_html)
new_elem.innerHTML = new_html;
// .append(html)
new_elem.innerHTML += ' ' + new_html;
// .append(element)
document.querySelector('body').appendChild(new_elem);
Notes
You cannot append <script> tags using innerHTML. You'll have to use appendChild.
If your page is strict xhtml, appending a non strict xhtml will trigger a script error that will break the code. In that case you would want to wrap it with try.
jQuery offers several other, less straightforward shortcuts such as prependTo/appendTo after/before and more.
To copy HTML from one div to another, just use the DOM.
function copyHtml(source, destination) {
var clone = source.ownerDocument === destination.ownerDocument
? source.cloneNode(true)
: destination.ownerDocument.importNode(source, true);
while (clone.firstChild) {
destination.appendChild(clone.firstChild);
}
}
For most apps, inSameDocument is always going to be true, so you can probably elide all the parts that function when it is false. If your app has multiple frames in the same domain interacting via JavaScript, you might want to keep it in.
If you want to replace HTML, you can do it by emptying the target and then copying into it:
function replaceHtml(source, destination) {
while (destination.firstChild) {
destination.removeChild(destination.firstChild);
}
copyHtml(source, destination);
}
Few years late to the party but anyway, here's a solution:
document.getElementById('your-element').innerHTML += "your appended text";
This works just fine for appending html to a dom element.
.html() and .append() are jQuery functions, so without using jQuery you'll probably want to look at document.getElementById("yourDiv").innerHTML
Javascript InnerHTML
Code:
<div id="from">sample text</div>
<div id="to"></div>
<script type="text/javascript">
var fromContent = document.getElementById("from").innerHTML;
document.getElementById("to").innerHTML = fromContent;
</script>

Is there a cross-browser css way to decorate only last word in a span block?

I need to show user's list which should look like in the example below:
Helen Burns Edward
Fairfax Rochester Bertha
Antoinetta Mason Adèle
Varens
Is there a way to achieve this without using javascript? Each row should be one span, i.e. <span>Helen</span><span>Burns</span> is not acceptable.
No, there is not. You are going to have to use some form of scripting to accomplish this if you don't want your last names to be in their own tags.
To the browser, each row is an element, and the "words" themselves have no separate meaning as far as CSS is concerned. You must place the words in different tags in order to do what you want.
The browser does not automagically know what part of the name is the last name so you have to add extra markup to achieve what you want.
There's no solution for common used browser for know using only CSS. You should use javascript or HTML + CSS as you already made.
without pure css this is impossible (as you don't want a separation in the markup)...
<span>Monty Burns</span><br />
<span>Bart Simpson</span>
<script type="text/javascript">
$(document).ready(function() {
var spans = $('span');
spans.each(function(index, element) {
var span = $(element);
var spanText = span.text();
var spanTextArray = spanText.split(' ');
var spanTextArrayLength = spanTextArray.length;
var lastName = spanTextArray[spanTextArrayLength -1];
spanTextArray.pop();
var firstName = spanTextArray.join(' ');
span.text(firstName);
var spanLastName = $('<span/>');
spanLastName.css('font-weight', 'bold');
spanLastName.css('margin-left', '5px');
spanLastName.appendTo(span);
spanLastName.text(lastName);
});
});
</script>
working demo.
edit: if you do not want an extra span-tag in there, just change
var spanLastName = $('<span/>');
spanLastName.css('font-weight', 'bold');
to
var spanLastName = $('<strong/>');
I don't think this is possible with CSS because your example doesn't show any order:
Helen Burns
Edward Fairfax Rochester
Bertha Antoinetta Mason
Adèle Varens
I don't know why you might desire not to have an extra tag surrounding the last name (as other answers and comments have suggested), but if you are looking simply for minimalist mark-up, this works (no span even used):
Html:
<body>
First Middle <strong>Last</strong>
First Middle <strong>Last</strong>
First Middle <strong>Last</strong>
</body>
Css:
strong:after {content:' '; display: block;}
Which creates "rows" with your desired styling without anything more than a single tag (which could be a span rather than a strong if you desired).
Edit: Of course, this will not work for IE7 or under.

Categories

Resources