getElementByClass().setAttribute doesn't work
It's getElementsByClassName
, not getElementByClass
; details here. Note that IE does not support this function (yet).
getElementsByClassName
returns a NodeList of matching elements (rather than a single element), so:
var list, index;
list = document.getElementsByClassName("home1");
for (index = 0; index < list.length; ++index) {
list[index].setAttribute(/* ... */);
}
For this sort of thing, you may want to use a library like jQuery, Prototype, Google Closure, etc., to pave over the various browser differences for you. They can save you a lot of time and trouble compared with dealing with those differences yourself.
For instance, in jQuery:
$(".home1").attr(/* ... */);
...applies that attribute (via jQuery#attr
) to every element with the class "home1". Although in your particular case, you'd probably want jQuery#css
instead.
javascript getElementsByClassName and setAttribute not working
Ok, so there are a few problems here
1. You need to assign the function to the change event, not call the change event.
2. You don't use setAttribute on the style, you use that to set a attribute on a element.
3. You should be caching your elements.
window.onload = init;
var elementR, elementG, elementB, opacityElement;
function init(){
elementR = document.getElementById("colorR");
elementG = document.getElementById("colorG");
elementB = document.getElementById("colorB");
opacityElement = document.getElementById("Opacity");
// Set change events
elementR.onchange =
elementG.onchange =
elementB.onchange =
opacityElement.onchange = setColors;
}
function setColors(){
var r = elementR.value,
g = elementG.value,
b = elementB.value,
a = opacityElement.value,
preview = document.getElementsByClassName("previewAreaBox")[0];
preview.style.backgroundColor = 'rgba(' + r + ',' + g + ',' + b + ',' + a / 100 + ')';
}
Element.onchange() = something;
Won't work because onchange();
actually triggers the event and doesn't assign the function to it.
You can also use Array.join
for the rgba like so
var rgba = [elementR.value, elementG.value, elementB.value,
opacityElement.value / 100];
preview.style.backgroundColor = 'rgba(' + rgba.join(',') + ')';
Getting document.getElementByClassName is not a function error in console
Replce getElementByClassName
with getElementsByClassName
note that its plural(Elements
) with "s" at end and not singular(Element
)
the same class can be added to multiple objects hence, selecting by class name returns multiple items, not just one so it uses the plural form Elements
instead of Element as in case of getElementById()
as id must be unique and selecting by id will return only one DOM element
and, since the function getElementsByClassName
returns an array of elements elmnt.scrollIntoView()
won't work,
so you need to use the first element of the array as elmnt[0]
so you code will be
function myFunction() {
var elmnt = document.getElementsByClassName("filter-btn");
elmnt[0].scrollIntoView();
}
However, I would rather suggest using getElementById
if you want to select only one element and use as below(first give id IdGivenToTheAnchoreTag
to anchor tag)
function myFunction() {
var elmnt = document.getElementById("IdGivenToTheAnchoreTag");
elmnt.scrollIntoView();
}
element.setAttribute is not a function
or this:
var link = "http://www.someurl.com";
var preview = document.getElementById("preview"); //getElementById instead of querySelectorAll
preview.setAttribute("data", link);
Be sure to run the code after the element is created, or use jQuery code:
$( document ).ready(function() {
}
@Lazarus Rising mentioned,
Uncaught TypeError: Cannot read property 'setAttribute' of null
In that case, the element doesn't exist yet in the document. You need to run the code after the element is created, say after the load event or a script below the element.
setAttribute in for loop doesn't work as I expected
Based on your answer, I assumed that you are trying to modify the classes of an element. You can utilize classList
property for that purposes. I've cleaned up some of your codes and formatted it.
function showListItems() {
const searchField = document.getElementsByName("ingredientSearch")[0];
const items = document.getElementsByClassName("items");
searchField.addEventListener("keyup", function() {
const ingredientsList = document.getElementById("IngredientsList");
if (ingredientsList.classList.contains("noneDisplay")) {
ingredientsList.classList.remove("noneDisplay");
}
filterListItems(items);
});
}
function filterListItems(items) {
const inputText = document.getElementsByName("ingredientSearch")[0].value.toUpperCase();
for (let i = 0; i < items.length; i++) {
const itemsText = items[i].textContent.toUpperCase();
if (itemsText.indexOf(inputText) > -1) {
items[i].classList.remove("noneDisplay");
continue;
}
items[i].classList.add("noneDisplay");
}
}
showListItems();
As mentioned in the comments, I personally think that you can just filter and map based on an items
array into a ul
list, I think that way its simpler to do, easier to maintain and easier to read as well.
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<body>
<input id="input" placeholder="Search..." />
<ul id="ingredients-list">
<!-- List items will be created with javascript -->
</ul>
<script>
const updateList = (items = []) => {
const list = document.getElementById("ingredients-list");
// Clear list items
while (list.firstChild) {
list.firstChild.remove();
}
if (items && Array.isArray(items) && items.length > 0) {
// Rerender with new list items
items.forEach(item => {
const listItem = document.createElement("li");
listItem.appendChild(document.createTextNode(item));
list.appendChild(listItem);
});
}
};
const handleOnChange = e => {
const { value } = e.target;
updateList(
items.filter(item => item.toUpperCase().includes(value.toUpperCase()))
);
};
const items = [
"Apple",
"Asparagus",
"Baking Powder",
"Balsamic Vinegar",
"Vinegar",
"Wheat Flour",
"White Wine"
];
updateList(items);
const input = document.getElementById("input");
input.addEventListener("keyup", handleOnChange);
</script>
</body>
</html>
Working Demo using my approach : https://codesandbox.io/s/html-filter-list-nolnk?fontsize=14&hidenavigation=1&theme=dark
How do you change an element's attribute from document.getElementByClass within a for loop?
First of all you can’t set your own attributes like this. The correct code is:
document.getElementsByClassName("IPForm")[i].setAttribute("pattern", "somregex");
My second remark is that the function is getElementsByClassName()
not getElementByClassName()
.
Setting the name attribute dynamically
document.getElementsByClassName
will return a node list (like an array) of elements. So, you need to treat it like an array. Try this if you only have one element:
document.getElementsByClassName('cke_source')[0].setAttribute('name', "mymessage")
Why can't we chain javascript createElement() and setAttribute()?
The first code block of the question gives a "div" element as the output. If you run below code
console.log(someDiv1);
you can see the output of someDiv1 variable like this.
<div class="test"></div>
If you execute the above code before the second line of the first code block of the question you will get
<div></div>
as the output. Because it hasn't added the class attribute to the created "div" element yet. And by executing the second line it will add the class attribute to that "div" element.
But if you do the same thing to the someDiv2 variable the output will be undefined. That means the second code block of the question has no output. That's why it gives an error when trying to use appendChild(). But Why ????
The reason is the latter part of the second code block.
.setAttribute('class', 'someClass');
It sets the class attribute to the created "div" element. But doesn't output anything instead it just does something. Even though the former part of the second code block gives an output, the latter part is the one which gives the final output for being assigned to the variable. Since it doesn't give any output there is no value for someDiv2 variable.
But actually that second code block is executed without any problem. The only problem is the variable has no value. So it wouldn't give any errors until we are going to use the someDiv2 variable in somewhere. But the problem is to show the created "div" element we definitely have to use the someDiv2 variable.
So concatenating "setAttribute()" and "createElement()" is useless.
So what if do this instead of assigning to a variable.
document.querySelector(".container").appendChild(document.createElement('div').setAttribute('class', 'someClass');
NO. This would not work as well. You can understand it, since the concatenation of setAttribute() and createElement() doesn't give exact output, appendChild() function has no input too. So it gives errors.
This is same for other functions like setAttribute() and createElement(). Like if you try to concatenate,
- getElementsByClassName() and setAttribute()
- createElement() and classList.add()
- createElement() and className
- getElementById() and classList.add()
- getElementsByClassName() and className()
those will definitely be executed without any problem but no exact output. Actually those are some examples. There are many combinations like that.
Yes. we usually use that kind of concatenations exactly. But we have to bear in mind that it these kind of concatenations doesn't give any output. Specially if we use "createElement()" it will matter a lot. Because we have to show the output in somewhere.
Related Topics
How to Display Selected Image Without Sending Data to Server
CSS Position Absolute Making the Textbox Go Down
How to Find Which JavaScript Is Changing an Element's Style
How to Show the Child Div on Mouse Hover of Parent Div
Javascript: Hiding and Showing Div Tag with a Toggle Button
How to Disable a Specific Li Element Inside a Ul
Test If a Browser Supports a CSS Selector
Resize Bar for Sidenav in Angular Material Design
How to Make Bootstrap Off Canvas Nav Overlap Content Instead of Move It
How to Make a Rotated Element Height:100% of Its Parent
JavaScript Show Element on Click
Can JavaScript Change the Value of @Page CSS
Blend Mode:Multiply in Internet Explorer
How to Get Horizontal Scrollbars at Top and Bottom of a Div
How to Fix Chart Legends Width-Height with Overflow Scroll in Chartjs