Getting CSS Values from elements - javascript

I need to use the web storage api to store style changes of the elements on one page.
I actually have no clue how to do this but I thought I'd start by getting the CSS attribute that's been changed and storing it in an array. Im trying to follow what's going here and tailoring it to my problem.
this is what i've tried in order to get the values but im not sure if it's correct:
function newItem(){
var bgImg = document.getElementsByTagName('body').bgImg[0].style.getPropertyValue('background');
var wideScreen = getElementById('sidebar').style.getPropertyValue('display');
var playerColor = getElementById('video_container').style.getPropertyValue('background-color');
}
I am not sure if the code i've written above grabs the information I need.

You can use getComputedStyle().
getComputedStyle() gives the final used values of all the CSS properties of an element.
var element = document.getElementById('sidebar'),
style = window.getComputedStyle(element),
display = style.getPropertyValue('display');
var element = document.getElementById('video_container'),
style = window.getComputedStyle(element),
bg = style.getPropertyValue('background-color');

Related

Find all divs/elements with background image containing URL and remove text

I read this Replacing background image using jQuery not working and quite a few other things but I'm having issues with this one.
I'm trying to find all divs/elements that contain a background-image: url();. IF they contain a background image with https://website.com/imagepath/image.jpg I want to remove the "https://website.com" piece and leave it as a local url only i.e. "/imagepath/image.jpg"
I'd like to do this in pure JS but I'm not opposed to jQuery
This would be incredibly taxing on performance and I would not recommend doing it this way.
You would have to go through every single element on the page and check its computed style and then update that if it matches your provided string.
const searchStr = 'https://website.com/imagepath/image.jpg';
const replaceStr = 'https://website.com/newimage.jpg';
const body = document.getElementsByTagName('body')[0];
const elements = Array.from(body.getElementsByTagName('*'));
elements.map(element => {
const style = window.getComputedStyle(element);
if (!!style.backgroundImage.includes(searchStr)) {
element.style.backgroundImage = replaceStr;
}
});

Can I set a <div> with an ID that has been dynamically created?

In my program I am dynamically creating feedback boxes to respond to user input. My problem is, I don't know how many of these pieces of feedback will be outputted. I have created a function in my javascript that assigns an id to each new element I create at runtime by concatenating a string with a variable number - which is incremented after every time the constructor is called - and appending it to my CSS class for styling, however I'm not sure how to reference a varying id in my html so that they actually appear on the screen.
var counter = 0;
function constructFeedbackBox() {
counter++;
var newElement = 'toast' + counter;
var i = null;
i = document.createElement('div');
i.id = newElement;
i.className = ".toastStyle";
}
In addition, if there are any problems with the way I've done my javascript to create my Id and/or append it to my class, the info would be much appreciated (I'm still pretty new to this)
First of all, document.createElement() takes a tagName as an input. If you are making divs, your line should read document.createElement('div');.
You can then do i.setAttribute(id, 'toast' + counter);.
What are you trying to accomplish overall with this? Maybe there is a better approach. Also worth noting that IDs must be unique, so be careful about that.

Referencing variables in an img src to make a link?

I'm trying to put a string and a number together so a variable is in an image link, and so the variable formed by the string and number's value would display in the link, but instead the raw name just displays, not the variable's value.
var link1 = 'restOfLink.gif';
var myFunction = function(number){
var imgLink = 'http://i60.tinypic.com/';
var randomNumber = Math.floor((Math.random()*5)+1);
$("div").append("<img src = '"+imgLink+'link'+randomNumber+"'/>");
}
randomNumber won't always be 1 but let's just assume it is.
The link shows up as http://i60.tinypic.com/link1.gif
Any help on that? I'm trying to make an app that displays a new random image when a div is clicked. (the code above isn't all of the code, but it's enough to cover my problem)
If you wanted to create a dynamic img element with a variable as the link or part of it you could do:
//These are just example variables, you can use your own the same way.
var imgPath = '/images/blog/';
var size = '200x450';
document.createElement('img').src = imgPath + 'yourImage' + size + '.png';
JsFiddle Demo.
For your example i would suggest creating an array of links that you can access using a random number, for example:
var links = ['restOfLink.gif', 'anotherexample.png', 'yetanother.jpg'];
To select a particular image from inside the links array you need to pass it the index it occurs at, with 0 being the first.
So for example:
links[0] --> "restOfLink.gif"
links[1] --> "anotherexample.png"
links[2] --> "yetanother.jpg"
See this JsFiddle demo using this method.
You should create the link string by concatenating the different parts in Javascript, and update the img src attribute afterwards. Something like:
var bar = 3;
var linkString = "http://www.foo.com/image_number_" + bar + ".jpg";
document.getElementById("yourImgId").src = linkString;
Best.
Dont know what you want. A JSFiddle would help as suggested but here is my try at a answer:
string = "lol";
number = 1;
source = string+number;
$(".element").attr('src', source+".jpg");
You need JQuery for this though.

JavaScript Retrieving the unique 'id' of div elements with just a class?

When making a JavaScript script to iterate through a set of elements with the same class name, you can alter each of their properties individually.
How does the script know which element to edit if they don't have unique IDs? If they do in fact have unique ID's, how do you retrieve them? Using alert(); to display what is held in the node array from a simple document.getElementsByClassName(''); seems to display the type of element.
Could I actually store these results in an array for later use?
If on the documents load, I fetch an array of elements with a certain class name:
<script>
var buttonArray = document.getElementsByClassName('button');
</script>
Then iterate through this, and add the result at 'r' position to an object:
<script>
var buttonArray = document.getElementsByClassName('button');
var buttonObject = {};
for(r=0;r<buttonArray.length;r+=1)
{
buttonObject[buttonArray[r]] = [r*5,r*5,r*5];
}
</script>
Would I be able to find the array for each individual element with classname 'button' like so:
<script>
var buttonArray = document.getElementsByClassName('button');
var buttonObject = {};
function changeCol(buttonID)
{
var red = buttonObject[buttonID][0];
var green = buttonObject[buttonID][1];
var green = buttonObject[buttonID][2];
buttonID.style.backgroundColor = "rgb("+red+","+green+","+blue+")";
}
for(r=0;r<buttonArray.length;r+=1)
{
buttonObject[buttonArray[r]] = [r*5,r*5,r*5];
buttonArray[r].onclick = function(){ changeCol(this); };
}
</script>
I thought the this part of onclick = function(){ changeCol(this); }; would hold the same unique ID as I stored in the buttonObject object, as the variable name that held the array?
Should this work? I can't seem to get it to on my web page, so instead, I used the buttons innerHTML in the buttonObject as the variable name that held the array for that object. The problem with that, is that I will probably need two or more buttons to have the same innerHTML.
Here's the webpage as it currently is:
http://www.shadespeed.com
I need to re-make the script to allow buttons to have the same name.
Any tips / advice would be greatly appreciated.
Many thanks!
- Dan. :)
Let's say I have a deck of cards spread out on my desk, face up. I want to flip over all the red ones. I might do this:
desk.getCardsByColour("red").forEach(flipit);
// note, obviously not real JavaScript for a not real situation :p
So I scan through my cards, finding all the red ones. Then I flip them over. What you're asking is basically "how do I know which cards to flip over if they don't have unique IDs?" Well, do I need an ID to iterate through a collection of objects, in this case a set of cards? Of course not.
(Note that while cards in a deck do have a unique property in their content, let's just assume that's the element's content and not an id attribute, kay?)
Now, here's how I'd do what you're doing:
for( r=0; r<buttonArray.length; r++) {
buttonArray[r].buttonObject = [r*5,r*5,r*5];
buttonArray[r].onclick = changeCol;
}
function changeCol(button) {
var red = button.buttonObject[0];
var green = button.buttonObject[1];
var blue = button.buttonObject[2];
button.style.backgroundColor = "rgb("+red+","+green+","+blue+")";
}

Beginner Javascript error with getAttribute

I've searched quite a bit on both google and stackoverflow, but a lack of knowledge on how to ask the question (or even if I'm asking the right question at all) is making it hard to find pertinent information.
I have a simple block of code that I am experimenting with to teach myself javascript.
var studio = document.getElementById('studio');
var contact = document.getElementById('contact');
var nav = document.getElementById('nav');
var navLinks = nav.getElementsByTagName('a');
var title = navLinks.getAttribute('title');
I want to grab the title attribute from the links in the element with the ID 'nav'.
Whenever I look at the debugger, it tells me that Object #<NodeList> has no method 'getAttribute'
I have no idea where I'm going wrong.
The nodetype and nodevalue for navLinks comes back as undefined, which I believe may be part of the problem, but I'm so new to this that I honestly have no idea.
The getElementsByTagName method returns an array of objects. So you need to loop through this array in order to get individual elements and their attributes:
var navLinks = nav.getElementsByTagName('a');
for (var i = 0; i < navLinks.length; i++) {
var link = navLinks[i];
var title = link.title;
}
Calling nav.getElementsByTagName('a') returns list of objects. And that list doesn't have getAttribute() method. You must call it on ONE object.
When you do:
navLinks[0].getAttribute('title')
then it should work - you will get title of the first matched element.
var navLinks = nav.getElementsByTagName('a');
getElementsByTagName returns multiple elements (hence Elements), because there can be multiple elements on one page with the same tag name. A NodeList (which is a collection of nodes as returned by getElementsByTagName) does not have a getAttribute method.
You need to access the property of the element that you actually need. My guess is that this will be the first element you find.
var title = navLinks[0].getAttribute('title');

Categories