Changing style of getElementsByClassName gives compile error - javascript

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');

Related

Javascript; selecting a nested element is throwing a "not a function" error

I need to select an element within another element (a button within a form). I'd normally use jQuery; which would look something like this:
element = $('#webform-client-form-1812 input[name="op"]');
But I can't use jQuery on this project so I tried:
element = document.getElementById("webform-client-form-1812").getElementsByName("op")[0];
But I'm getting the error:
Uncaught TypeError: document.getElementById(...).getElementsByName is not a function.
This seems like one of those issues where the solution will be embarrassingly obvious to others. But I've looked at this thoroughly and I can't spot my mistake. Can someone help me?
getElementsByName is only a method on document - unlike getElementsByClassName, it's not callable on individual elements.
Use querySelector instead, and you can use the same CSS selector you used in jQuery:
const element = document.querySelector('#webform-client-form-1812 input[name="op"]');
It's probably good to use querySelector or querySelectorAll instead of nested getElement... getElement calls whenever possible - it's less unnecessarily verbose and makes the code clearer. You can easily express a lot of complicated rules with a CSS selector string that would be quite unwieldy to code otherwise.
Because 'getElementsByName' and 'getElementById' can only supported by object 'document' and 'XMLDocument', you can compare with getElementByTagName.http://help.dottoro.com/ljlfpmux.php

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;
}

JSON return error as undefined when the value is numeric

not sure where the errors lies in what I am trying to achieve.
I am working with someone else's code and unfortunately they have used numbers for div ids in some places.
These number ids are used in various places and if I can, I want to find a way to keep things as they are.
So,
returning the following in JSON:
editorID: "1000"
And in my AJAX call i use that return like so:
var editorID = response.editorID;
CKEDITOR.instances.editorID.insertHtml('<br><img class="buildimage" src="http://www.buildsanctuary.com/phpLibs/bulletproof-master/src/userBuildImages/'+response.imageName+'"><br>');
However this gives me an error saying that the editorID is undefined.
As you can I already use a JSON response in my code, this works fine so its not a problem with datatypes etc.
I also tried to do:
alert(response.editorID);
which gave me the correct value.
When I tried putting a number directly into CKEditor insertHTML code it was showing my syntax errors so maybe thats the issue. If so, any work around for it?
Thanks. Craig.
To use a variable as a property, you have to use [] notation:
CKEDITOR.instances[editorID].insertHtml('<br><img class="buildimage" src="http://www.buildsanctuary.com/phpLibs/bulletproof-master/src/userBuildImages/'+response.imageName+'"><br>');
When you use .editorID, it's looking for a property named editorID, not 1000.
You also have to use this syntax when the property isn't a valid identifer. So if you wanted to put the number directly, you would write:
CKEDITOR.instances['1000'].insertHtml('<br><img class="buildimage" src="http://www.buildsanctuary.com/phpLibs/bulletproof-master/src/userBuildImages/'+response.imageName+'"><br>');

JQuery, html() on a table cell returns "undefined is not a function"

I've been having some problems with JQuery.
I have a HTML table with the names having the class .ulName
When I retrieve them with $('.ulName'), I have no problem. When I iterate over them with alert(), Chrome tells me they are indeed HTMLTableCellElement. But when I use the html() method on them, I get "Uncaught TypeError: undefined is not a function". I tried to use other methods to see how it would work (append() for example) but it did the same thing.
I also tried to change from a forloop to $.each but it did the same thing.
And finally, I also tried $.parseHTML but it returns null.
Here is the code source, I hope you can help me with my problem because I don't see why it wouldn't work. Thank you in advance for your answers.
$('#ulFilter').on('input', function () {
var uploads = $('.ulName');
for (var i=0; i < uploads.length; i++) {
alert(uploads[i].html());
}
});
Using the indexer gets the raw DOM element, not the jQuery object. See this question.
The raw element does not have a function called html, but instead a property called innerHTML.
Here are a few solutions:
using uploads.eq(i) instead of uploads[i]
using $(uploads[i]) instead of uploads[i]
using uploads[i].innerHTML instead of uploads[i].html()
$(".ulName") returns you a NodeList.
So you can use,
var uploads = $(".ulName");
$.each(uploads, function() {
$(this).html();
});

Trouble converting Javascript array into JQuery for IE7 compatibility

I am trying to convert a line in Javascript so that the functionality works in IE7. Below is the code I am trying to convert. Obviously IE doesn't like the class attribute being set which is where the issue occurs. So my solution was to translate it using JQuery for browser compatibility. But I am having trouble converting the array into something JQuery understands.
This is the code:
ulAccNm.children[iVal].setAttribute("class", "show");
I have tried the following, but it doesn't work correctly.
$(ulAccNm).children(jQuery.inArray("iVal")).addClass('show').removeClass('hide');
The variable of iVal translates into the total number of children to the parent and loops through each to determine to add a class or not. Any help would be greatly appreciated.
I'm guessing a lot here, but I think this will translate:
$($(ulAccNm).children()[iVal]).addClass('show').removeClass('hide');
However, if you want to do this to ALL the children, you don't need an explicit loop with iVal. Just use
$(ulAccNm).children().addClass('show').removeClass('hide');
You may just want to try changing your loop structure from a for loop to the jQuery.each method:
$(ulAccNm).children().each(function () {
// Decide if the class needs to be changed
if (needsToBeChanged)
$(this).addClass('show').removeClass('hide');
})
Ended up fixing by using Kevin B's suggestion of .children().eq(ival) and this makes it work

Categories

Resources