Reading argument via vanilla Javascript - javascript

Looking for a little advice with the following - i'm passing an onclick event with an argument into JS as follows:
<div class="artistthumb" id="jamesPaterson1" onclick="artistModalOpen('jamesPaterson1')"></div>
This enters the following JS function:
function artistModalOpen(x1) {
var imagePath = document.getElementById(x1).style.backgroundImage;
console.log(x1);
console.log(imagePath);
}
The CSS for the id is:
background-image: url(../img/james_paterson_1.jpg);
So far i'm just logging the 2 console outputs - the first is fine, console displays argument x1 as expected: jamesPaterson1
The second console log doesn't show anything.
I would have expected to see url(../img/james_paterson_1.jpg)
Anyone know why this isn't happening?
Many thanks in advance!

Try getComputedStyle
var imagePath = getComputedStyle(document.getElementById(x1))
.getPropertyValue('background-image');
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
The window.getComputedStyle() method returns an object that reports
the values of all CSS properties of an element after applying active
stylesheets and resolving any basic computation those values may
contain. Individual CSS property values are accessed through APIs
provided by the object or by simply indexing with CSS property names.

Related

Changing style of getElementsByClassName gives compile error

I am trying to change the style of all of the elements which I received by calling the method getElementsByClassName. The thing is that it does work when it has compiled before (I commented these rows out to let it compile), it just says the error in the cmd. After it compiled I just set the lines back to normal, they keep giving errors but are working in the browser. Any thoughts on this weird behavior?
When commented out:
When not commented and giving errors:
I think the problem is with TypeScript. You should try this workaround
var texts = document.getElementsByClassName("section_text") as HTMLCollectionOf<HTMLElement>;
I had a similar issue when trying to pull off something with angular. The problem is that the getElementsByClassName returns a nodelist, not a normal array, so you can't access properties like you're trying to. You can read more in about it in this answer.
you can simply addClass():
CSS
.newStyle{
width:100%;
float:left;
}
Use Jquery
$('.section_text input').addClass('newStyle');
Use Javascript
document.querySelector('.section_text input').classList.add('newStyle';
getElementsByClassName returns a nodelist. Access properties directly.
let hiddenLocales = document.getElementsByClassName('localeMatch') as HTMLCollectionOf<HTMLElement>;
let hideParentNode = hiddenLocales[0].parentElement;
hideParentNode?.classList.add('newStyle');

Getting element from DOM with jQuery

EDIT:
JSFIDDLE here. I am trying to mirror DESKTOP 1 to MOBILE 1 elements (same for #2) in the fiddle. The error is shown in console.
Got to DESKTOP 1 and select NEW RATE from the list. Have the console opened to see the issue. Thanks!
I get an element from my layout with this command:
var eqTaxSelect = $('table#mob-tab-' + num).find('select.tax_rate').get();
I then try to toggle it:
toggleField($(eqTaxSelect), $(eqTaxSelect).nextElementSibling); <-- FAILS
function toggleField(hideObj, showObj) {
hideObj.style.display = 'none'; <-- FAILS HERE
showObj.style.display = 'inline';
showObj.focus();
}
with:
Uncaught TypeError: Cannot set property 'nextElementSibling' of undefined
What am I doing wrong when assigning the element to my variable? This function works for this inside click event listeners for example.
Thanks!
The HTML I am toggling came from this forum, essentially a select with a hidden input so new entries can be added as well as using an entry from the options list.
What am I doing wrong when assigning the element to my variable?
You are passing jQuery() objects, where toggleField expects DOM elements. jQuery() does not have a .nextElementSibling method. Remove calls to jQuery() at
toggleField($(eqTaxSelect), $(eqTaxSelect).nextElementSibling);
replace with
toggleField(eqTaxSelect, eqTaxSelect.nextElementSibling);
to pass DOM elements to toggleField.
test with
console.log(eqTaxSelect)
see on inspector (CTRL+SHIF+I CHROME). if this is ok,
just do this
toggleField(eqTaxSelect, eqTaxSelect.nextElementSibling)
withouth "$"
The reason why your statement
toggleField(eqTaxSelect, eqTaxSelect.nextElementSibling);
fails is because of the way you are populating the eqTaxSelect
var eqTaxSelect = $('table#mob-tab-' + num).find('select.tax_rate').get();
It should be modified as
var eqTaxSelect = $('table#mob-tab-' + num).find('select.tax_rate').get(0);
reason being, get() without an index returns an array and the way you are operating, you are expecting an single dom element.
jQuery documentation for get()

Using a JS function to apply a new fill style to multiple SVGs does not work as expected

Here is my codepen, it's got a ton of comments in JS section since that is a core part of what I am learning still.
When I use "getELementsByClassName" or "querySelectorAll" to apply a new fill to an SVG, the console gives me errors. "getElementById" works, however I have multiple SVGs I would like to apply the change to.
If you press and hold on "click me", you see 3 lightning bolts. The program runs a code when you click to generate a hex value which is then applied to the 3 solid lightning bolts, and eventually the background of the page. The lightning bolts are SVGs. I have given each a shared class (".solids"), and unique IDs (#solids1, etc). However, using this:
document.getElementsByClassName (".solids").style.fill = "#" + newHexString;
...no changes are applied to the svgs at all. (Line 48 in the JS pane.) The console gives this error: "Uncaught TypeError: Cannot set property 'fill' of undefined"
Likewise, I have seen a few suggestions here on Stackoverflow and elsewhere to use .querySelector and .querySelectorAll and neither work. (Line 51, JS pane.) I also see a similar console error when trying this.
document.querySelectorAll(".solids").style.fill = "#" + newHexString;
But a long list of 'getElementById' works just fine. :/
I would love thoughts as to what I can do more efficiently, and why these other two routes don't work?
Both getElementsByClassName and querySelectorAll return (respectively) a HTMLCollection and a NodeList object, that's why the property style is undefined (there is no such property on HTMLCollection and NodeList objects) and you get the error because you try to access the fill property on an undefined value. The getElementById method returns an instance of Element (not a collection), that's why the style property is defined and you don't get any error.
I'm surprised querySelector doesn't work as it actually returns an element (like getElementById). Are you sure you got an error with it?
To apply the changes on all the elements, you need to iterate over the list returned by getElementsByClassName or querySelectorAll and set the style.fill property on each of them, like so:
var elements = document.getElementsByClassName('my-element');
for (var i = 0; i < elements.length; i++) {
elements[i].style.fill = '#' + newHexString;
}

Getting element using withName of Number in UIAElementArray

I am trying to get to a element (using javascript) which is inside UIAElementArray that has a number name like 1.
So when I try to get the element say with
array()["1"]
I am still getting the element at the index 1, instead of element which has a name/key value of 1.
Before some of you shoo me off to apple documentation, I found this and tried using firstWithName and withName
array().firstWithName("1")
but now I am getting a weird error "-[__NSCFNumber length]: unrecognized selector sent to instance 0x7c81ab0"
I haven't used length explicitly anywhere, what does the error mean and how do I get out of this?
I do not know exactly regarding the error but I know how to get required element. Try this one:
var predicate = "name contains '1'";
var requiredObj = mainWindow().popover().staticTexts().firstWithPredicate(predicate);
Hope this will help.

Firefox 5 gives all CSS when running getComputedStyle

Using firefox 5 when i run
window.getComputedStyle(document.getElementsByTagName("img")[0], null);
I get the complete css file, instead of the styles applied onto the "img" tag.
I ran this on https://developer.mozilla.org/en/DOM/window.getComputedStyle
Anyone knows of a workaround?
I know this is an older post, but for anyone landing here.
Basic idea: you need to call the getPropertyValue() method on the object returned by window.getComputedStyle().
See this fiddle: http://jsfiddle.net/zupa/jyyt9/
MDN states you don't need to call document.defaultView.getComputedStyle() but window.getComputedStyle
Note that window.getComputedStyle() returns used values not computed values. (See previous link.)
Compatibility tables: MDN, quirksmode
It should give you an object of type ComputedCSSStyleDeclaration that includes all styles that have been set. This includes all possible styles and not only those styles that have been manipulated by you in some way.
In order to get a specific rule, use for example:
window.getComputedStyle(document.getElementsByTagName("img")[0], null)['borderLeftColor'];
This gives the left border color without distinguishing how the value as specified / calculated.
To get a list of the available entries print the object to Firebug's console:
console.dir(window.getComputedStyle(document.getElementsByTagName("img")[0], null));
Use this :
document.defaultView.getComputedStyle(document.getElementsByTagName("img")[0], "");

Categories

Resources