JS: Selecting a DIV based on its onClick value - javascript

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>

Related

Changing attributes with click and querySelector not fully functioning

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>

How would I get an alert to appear when I click on an a button in a class?

I have several buttons in my webpage in the 'addbutton' class and I want an alert to pop up any time any one of them is clicked. How would you do this?
Here are some JS pieces of code I have already tried (that have not worked):
addbuttons = document.getElementsByClassName("addbutton")
addbuttons.onclick {
for (var i=0; i<addbuttons.length; i++) {
alert("hi")
}
document.getElementsByClassName("addbutton").onclick = function() {
alert("hi")}
And my HTML:
<input type="checkbox">
<p>Breakfast:</p>
<button class="addbutton">+</button>
<div></div>
<br>
<input type="checkbox">
<p>Mid-Morning:</p>
<button class="addbutton">+</button>
<div></div>
<br>
document.getElementsByClassName("addbutton") returns an Array(HTMLCollection to be precise).
Also, you need to set the onclick to a function, you cannot use the syntax .onclick { }.
To set a listener for every button you will need to use a for loop somewhat like this
for(let i = 0; i < addbuttons.length; i++){
addbuttons[i].onclick = function(){
alert('Works!')
}
}
Or if you are using ES6
for(let addButton of addbuttons){
addButton.onclick = function(){
alert('Works!')
}
}
Probably relevant links,
https://www.w3schools.com/js/js_loop_for.asp
https://www.w3schools.com/jsref/event_onclick.asp
Let's define your event:
function myEvent() {
alert("hi");
}
Now let's get your elements by class name, loop them and add an event listener to them:
for (let btn of document.getElementsByClassName("addbutton")) btn.addEventListener("click", myEvent);
Your mistake was that you assumed that you have an onclick for the set of elements, returned by getElementsByClassName, however, you only have onclick for the elements inside the set.

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