Changing attributes with click and querySelector not fully functioning - javascript

I've written this to change the background of a div that represents hours on a daily planner. The first instance (onclick) works but the others don't. Do I need to give each .container their own id and their own function?
var changeStatus = document.querySelector("#changeStatus");
var container = document.querySelector(".container");
changeStatus.addEventListener("click", function () {
container.setAttribute("class", "filled");
}

querySelector() is designed to return a single element only. If there are multiple elements matching the .container selector then it will only return the first.
In your case you need to use querySelectorAll() to retrieve all relevant elements, then you need to loop through them to update the class.
var changeStatus = document.querySelector("#changeStatus");
var container = document.querySelectorAll(".container");
changeStatus.addEventListener("click", function () {
container.forEach(el => el.setAttribute("class", "filled"));
});

You can add click listener with loops, something like this:
changeStatus.addEventListener("click", function () {
for(var i=0; i<container.length; i++) {
container[0].setAttribute("class", "filled");
}
}

Here's an example with querySelectorAll as #pilchard answered above:
var changeStatus = document.querySelector("#changeStatus");
var containers = document.querySelectorAll(".container");
changeStatus.addEventListener("click", function () {
containers.forEach(function (container) {
container.setAttribute("class", "filled");
});
});
.filled {
color: #f00;
}
<button id="changeStatus">change status</button>
<div class="container">container 1</div>
<div class="container">container 2</div>
<div class="container">container 3</div>

Related

JS: Selecting a DIV based on its onClick value

I have several different divs with same class, no id and only their onClick function separating them so they are uniquely identifiable, like this:
<div class="nest" onclick="nested.selection('VALUE1'); return false;">
... something inside the div ...
</div>
<div class="nest" onclick="nested.selection('VALUE2'); return false;">
... something inside the div ...
</div>
I would need to find and delete an entire div based on the specified onClick value, but since I cannot use getElementById, Class or Name, how is this lookup achievable with JS (not jQuery)?
try this
document.querySelector('[onclick="nested.selection(\'VALUE2\'); return false;"]').remove()
elements = document.querySelectorAll('.nest');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', (event) => {
const item = event.target;
item.parentNode.removeChild(item);
});
}
This code will remove div after clicking on it.
Im attaching event handler to all 'nest' elements and then after clicking on specific item removing it.
try this;
var nested = {
selection: function (a, e) {
var element = e.currentTarget;
element.parentNode.removeChild(element);
}
}
html
<div class="nest" onclick="nested.selection('VALUE1',event); return false;">
... something inside the div ...VALUE1
</div>
<div class="nest" onclick="nested.selection('VALUE2',event); return false;">
... something inside the div ...VALUE2
</div>
You don't need to click anything here. Just pass the argument. Like so:
deleteWithArg('VALUE1');
function deleteWithArg(deleteElement) {
var nst = document.getElementsByClassName("nest");
for(var i = 0; i < nst.length; i++)
{
let atr = nst.item(i).getAttribute('onclick').match(/'([^']+)'/)[1];
if (atr == deleteElement) {
nst.item(i).parentNode.removeChild(nst.item(i));
}
}
}
deleteWithArg('VALUE1');
<div class="nest" onclick="nested.selection('VALUE1'); return false;">
... something inside the div with value VALUE1...
</div>
<div class="nest" onclick="nested.selection('VALUE2'); return false;">
... something inside the div with value VALUE2...
</div>

Binding an event listener to multiple elements with the same class

I'm trying to apply the onclick event with JavaScript to the following elements:
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
If I click on the first element (with index [0]) then this works, but I
need this event applicable for all classes:
document.getElementsByClassName('abc')[0].onclick="function(){fun1();}";
function fun1(){
document.getElementsByClassName('abc').style.color="red";
}
.onclick does not expect to receive a string, and in fact you don't need an extra function at all.
However, to assign it to each element, use a loop, like I'm sure you must have learned about in a beginner tutorial.
var els = document.getElementsByClassName('abc');
for (var i = 0; i < els.length; i++) {
els[i].onclick = fun1;
}
function fun1() {
this.style.color = "red";
}
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
To expand on the solution provided by #rock star I added two small additions to the function. First it is better to add / reemove a class (with an associated style rule) to an element than directly applying the stylerule to the element.
Secondly - on the click event - this will now remove the red class (and therefore style) from the previously selected element and add it to the new element. This will allow only one element to be red at a time (in the original solution any element that was clicked would become red).
var els = document.getElementsByClassName('abc');
for (var i = 0; i < els.length; i++) {
els[i].onclick = fun1;
}
function fun1() {
var oldLink = document.getElementsByClassName('red')[0];
if(oldLink) {oldLink.classList.remove('red')};
this.classList.add('red');
}
.red {
color:red;
}
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
This works:
<body>
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
<script>
var elements = document.getElementsByClassName('abc');
for(var i = 0, max = elements.length; i < max; i += 1) {
var clickedElement = elements[i];
clickedElement.onclick=function (){
fun1(this);
};
}
function fun1(element){
element.style.color="red";
}
</script>
</body>

Select Child ByClassName Javascript

I have many divs like the following rendering on the same page:
<div class="contentUser">
<div class="innerContent">
Some data
</div>
<div class="contentButtonWrap">
Some buttons
</div>
</div>
I need to trigger a style change on "contentButtonWrap" when "contentUser is clicked".
I don't know how I can select a child element of a certain class name. Notice that the number of elements that can be rendered within "contentUser" changes from div(contentUser) to div. But there is all ways only one "contentButtonWrap" element within "ContentUser".
This is what I have:
function avoidHover() {
var userDivs = document.getElementsByClassName('contentUser');
[].forEach.call(userDivs, function(e){
e.click = function(){
var target = e.getElementsByClassName('contentButtonWrap');
target[0].style.backgroundColor='green';
};
});
};
"onclick" instead of "click". Sorry about that...
function avoidHover() {
var userDivs = document.getElementsByClassName('contentUser');
[].forEach.call(userDivs, function(e){
e.onclick = function(){
var target = e.getElementsByClassName('contentButtonWrap');
target[0].style.backgroundColor='green';
};
});
};
Here is my take at it : http://jsfiddle.net/cdL51w2g/
function avoidHover() {
var userDivs = document.getElementsByClassName('contentUser');
for(var i=0; i<userDivs.length; i++){
userDivs[i].onclick = function(){
var target = this.getElementsByClassName('contentButtonWrap');
target[0].style.backgroundColor='green';
};
}
};
I changed the way to access the children in the parent divand used the function onclick instead of click in the question.

getElementsByClassName get single element

I need to add an EventListener function on every div with a certain class, I tried this:
var a = document.getElementsByClassName('linkto');
for (var i = 0; i<a.length;i++) {
a[i].addEventListener('click',function(){
console.log(a);
}); }
But that gives me all the divs. My divs are generated in a foreach loop:
#foreach($faqs['My_Stay'] as $faqheading)
<div class="row lowboarder linkcolor-darkblue linkto">
{{ link_to('#div'.$faqheading->id,$faqheading->heading) }}
</div>
#endforeach
Is there a good way to determine which div was clicked on?
try like below, "this" inside your click function refer to the clicked div
for (var i = 0; i<a.length;i++) {
a[i].addEventListener('click',function(){
console.log(this.innerText);
}); }

Use function to remove divs after a sepecified div

HTML:
<div class="page">111111</div>
<div class="page">222222</div>
<div class="page">333333</div>
<div class="page">444444</div>
<div class="page">555555</div>
JavaScript:
var div = document.getElementsByClassName("page");
for (i = 0; i < div.length; i++) {
bt = document.createElement("button");
bt.innerHTML = "kill my followings";
div[i].appendChild(bt);
bt.onclick = function (i) {
return function () {
kill(div[i]);
}
}(i);
}
function kill(obj) {
// ...
}
See FIDDLE here.
I constructed some divs which class="page". I used JavaScript to add buttons to each div, and add onClick event to each of them.
I need to remove the divs after my current operating div. e.g, If user click button in No.3 div, No.4 and 5 should be removed.
How to realized it?
(if not necessary, the structure of original html is not allowed to change)
Thanks a lot!
This should be the simplest way to go:
function kill(obj) {
while (obj.nextSibling) {
obj.parentNode.removeChild(obj.nextSibling);
}
}
DEMO: http://jsfiddle.net/BtSKJ/3/

Categories

Resources