remove this.class function Javascript - javascript

I have a function connected to a class, that lets me remove it by className.
the problem I have is when I have two elements with the same class name. the function close both of the classes and not only the one that's selected.
I think that i use use a element.this function, but when I try it, none of the classes removes.
Any ideas ?
function CloseEvent(){
var CloseEvent = "close";
var addClassArr= document.getElementsByClassName(CloseEvent);
for(var i=0; i<addClassArr.length; i++){
var addClass = addClassArr[i];
addClass.addEventListener("click", closebutton, true);
}
function closebutton() {
var classToRemove = "dice-window-wrapper";
var elems = document.getElementsByClassName(classToRemove);
for (var i = 0; i < elems.length; i--) {
elems[i].parentNode.removeChild(elems[i])
}
}
}
CloseEvent();

the function close both of the classes and not only the one that's selected.
That's wrong, since more than one are selected via document.getElementsByClassName - and all of them are removed correctly.
Instead of selecting elements by their class name, select the one on which the event was fired at.
function closebutton(e) {
var elem = e.target; // or just the "this" keyword
// elem is the <div class="close" />
var wrapper = elem.parentNode.parentNode;
// wrapper is the <div class="dice-window-wrapper" />
wrapper.parentNode.removeChild(wrapper);
}

Updated the html code to reflect the html used on your site.
<div class="dice-window-wrapper">
<div class="dice-menubar-wrapper">
<div class="close">
close one
</div>
</div>
</div>
<div class="dice-window-wrapper">
<div class="dice-menubar-wrapper">
<div class="close">
close one
</div>
</div>
</div>
then here is how to remove the clicked element:
function CloseEvent(){
var CloseEvent = "close";
var addClassArr= document.getElementsByClassName(CloseEvent);
for(var i=0; i<addClassArr.length; i++){
var addClass = addClassArr[i];
addClass.addEventListener("click", closebutton, true);
}
function closebutton(e) {
var classToRemove = " "+"dice-window-wrapper"+" ";
var obj=e.target;
while((" "+obj.className+" ").indexOf(classToRemove)==-1){
obj=obj.parentNode;
}
if(obj.tagName.toLowerCase()!="div"){
console.log("something wrong in closebutton");
return;
}
obj.parentNode.removeChild(obj);
}
}
Note that this doesn't work at all in IE8 because getElementsByClassName is not supported not is the event passed in this way and there might be a problem with addEventListner. That's why I usually use jQuery.

You should be able to identify the object calling a JS function by using this to identify the triggering element like
function closebutton() {
this.parentNode.removeChild(this);
}
e.g. Delete the SO logo!
function notSO(){this.parentNode.removeChild(this);}
document.getElementById("hlogo").addEventListener("mouseover", notSO, true);

Here's your modified code:
function CloseEvent(){
var CloseEvent = "close";
var addClassArr= document.getElementsByClassName(CloseEvent);
for(var i=0; i<addClassArr.length; i++){
var addClass = addClassArr[i];
addClass.addEventListener("click", function(){ closebutton(this) }, true);
}
function closebutton( elem ) {
var classToRemove = "dice-window-wrapper";
//var elems = document.getElementsByClassName(classToRemove);
//for (var i = 0; i < elems.length; i--) {
// elems[i].parentNode.removeChild(elems[i])
//}
// you have passed the element to be removed, directly remove it
elem.parentNode.removeChild(elem);
}
}
CloseEvent();

Related

Passing arguments when setting onclick in Javascript

Alright, i've been looking everywhere for a way to do that.
I have a list of buttons that are supposed to delete a table row when they are clicked on. I can't write a onclick directly in the HTML file because some of those table row can be added or deleted by the user, so I added them in Javascript:
function setOnclick() {
var deleteBtn = document.getElementsByClassName("delete-btn");
for(var i = 0; i < deleteBtn.length; ++i){
deleteBtn[i].onclick = deleteArticle(/*(this)*/);
}
}
function deleteArticle(article){
/* delete the article row from table */
}
Now I cannot put any arguments because if I put () at the end of the function it's going to launch it instead of just assinging it.
PS: Since this is an assignment, I'm not authorized to use jQuery.1
If you want to pass arguments to event listener, .bind() can be used:
function setOnclick() {
var deleteBtn = document.getElementsByClassName("delete-btn");
for(var i = 0; i < deleteBtn.length; ++i){
deleteBtn[i].onclick = deleteArticle.bind(deleteBtn[i], 'some_more_parameter');;
}
}
function deleteArticle(param){
// DOM operation with "this"
alert(this.innerText + ' & ' + param);
}
setOnclick();
<button class="delete-btn">
xxx
</button>
<button class="delete-btn">
yyy
</button>
you should put
...
deleteBtn[i].onclick = deleteArticle
...
function deleteArticle(){
this.parentNode.removeChild(this);
}
You can use clouser function.
function setOnclick() {
var deleteBtn = document.getElementsByClassName("delete-btn");
for(var i = 0; i < deleteBtn.length; ++i){
let article = deleteBtn[i];
article.onclick = function() {
deleteArticle(article);
}
}
}
function deleteArticle(article){
/* delete the article row from table */
}

How do I add target=“_blank” to a link within a div with an specific class name?

I´m trying to add target=“_blank” to all the links within the divs with an specific class name. I know how to do it with an ID:
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
But i´m trying to replicate the same, using classes instead of IDS. Any ideas of a how to do this without jquery?.
Thanks in davanced!
You can use querySelectorAll() and include a CSS selector. So if your class name is link-other:
document.querySelectorAll('.link-other a')
.forEach(function(elem) {
elem.setAttribute('target', '_blank');
})
<div class="link-other">
Wikipedia
Google
</div>
Use querySelectorAll and loop just like you did.
var anchors = document.querySelectorAll(".link_other a");
Or you can use getElementsByClassName and nested loops.
var parents = document.getElementsByClassName(".link_other");
for (var i = 0; i < parents.length; i++) {
var anchors = parents[i].getElementsByTagName("a");
for (var j = 0; j < anchors.length; j++) {
anchors[j].setAttribute('target', '_blank');
}
}
You can use document.querySelectorAll() which takes a css expression:
var anchors = document.querySelectorAll('.my_class a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
Or (ab)using the array prototype:
[].forEach.call(document.querySelectorAll('.my_class a'), function(el) {
el.setAttribute('target', '_blank');
});
You should also consider using addEventListener instead of window.onload:
window.addEventListener('load', function() {
// ...
});
Or the more appropriate:
document.addEventListener('DOMContentLoaded', function() {
// ...
});
You can also use the old school <base> element which will can set defaults for all a tags:
var base_el = document.createElement('base');
base_el.setAttribute('target', '_blank');
document.head.appendChild(base_el);
To achieve your expected result use below option
var addList = document.querySelectorAll('.link_other a');
for(var i in addList){
addList[i].setAttribute('target', '_blank');
}
Codepen - http://codepen.io/nagasai/pen/QEEvPR
Hope it works

Can you use "this" attribute on onclick of an HTML tag?

Can you use the this tag for the onclick on an HTML tag?
Here's my JS code...
function changeImage() {
this/*<-- right there <--*/.src=a;
}
document.getElementsByTagName('img').onclick = function(){
changeImage();
} ;
Am I doing something wrong?
Use it this way...
function changeImage(curr) {
console.log(curr.src);
}
document.getElementsByTagName('img').onclick = function(){
changeImage(this);
} ;
You could use the .call() method to invoke the function with the context of this.
In this case, you would use:
changeImage.call(this)
Example Here
function changeImage() {
this.src = 'http://placehold.it/200/f00';
}
document.getElementsByTagName('img')[0].onclick = function(){
changeImage.call(this);
};
As a side note, getElementsByTagName returns a live HTMLCollection of elements. You need to apply the onclick handler to an element within that collection.
If you want to apply the event listener to the collection of elements, you iterate through them and add event listeners like this:
Updated Example
function changeImage() {
this.src = 'http://placehold.it/200/f00';
}
Array.prototype.forEach.call(document.getElementsByTagName('img'), function(el, i) {
el.addEventListener('click', changeImage);
});
Or you could simplify it:
Example Here
Array.prototype.forEach.call(document.getElementsByTagName('img'), function(el, i) {
el.addEventListener('click', function () {
this.src = 'http://placehold.it/200/f00';
});
});
You are doing two things wrong.
You are assigning the event handler to a NodeList instead of to an element (or set of elements)
You are calling changeImage without any context (so this will be undefined or window depending on if you are in strict mode or now).
A fixed version would look like this:
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].onclick = function () {
changeImage.call(this);
};
}
But a tidier version would skip the anonymous function that does nothing except call another function:
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].onclick = changeImage;
}
And modern code would use addEventListener.
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].addEventListener('click', changeImage);
}
However, images are not interactive controls. You can't (by default) focus them, so this approach would make them inaccessible to people who didn't use a pointing device. Better to use controls that are designed for interaction in the first place.
Generally, this should be a plain button. You can use CSS to remove the default padding / border / background.
If you can't put a button in your plain HTML, you can add it with JS.
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
var image = images[i];
var button = document.createElement('button');
button.type = "button";
image.parentNode.replaceChild(button, image);
button.appendChild(image);
button.addEventListener('click', changeImage);
}
function changeImage(event) {
this.firstChild.src = a;
}

simple hover and hover out issue in javascript

I am trying to create hover and hover out via javascript.
I have
test.prototype.build = function(){
other codes...
link.href = '#';
link.innerHTML += 'test'
link.onmouseover = hover
link.onmouseout = hoverOut
other codes...
}
function hover(){
var div = document.createElement('div');
div.class='testDiv';
div.innerHTML = 'test';
$(this).prepend(div);
}
function hoverOut(){
var div = document.getElementsByClassName('testDiv');
div.style.display='none';
}
My task is to create a hover and hover out function. My problem is I am not sure how to hide the testDiv when the user hover out of the link.
getElementsByClassName doesn't seem to work in my case. Are there better way to do this in javascript? Thanks a lot!
document.getElementsByClassName('testDiv') returns an collection, not a single object, but you can probably just use this to refer to the current object. Since you showed some jQuery in your original code, I assume that is OK here.
function hoverOut(){
$(this).find(".testDiv").hide();
}
or, in plain javascript, it could be:
function hoverOut(){
var elems = this.getElementsByClassName("testDiv");
for (var i = 0; i < elems.length; i++) {
elems[i].style.display = "none";
}
}
Your hover and hoverOut code don't match though because you're creating a new div on hover every time in hover and then only hiding it in hoverOut so they will accumulate.
If you want to remove the div you added in hoverOut(), you can do that like this:
function hoverOut(){
$(this).find(".testDiv").remove();
}
or in plain javascript:
function hoverOut(){
var elems = this.getElementsByClassName("testDiv");
for (var i = 0; i < elems.length; i++) {
elems[i].parentNode.removeChild(elems[i]);
}
}

effect all nodes with a shared class

I have a page with div's that each have multiple classes.
<div class='publication parent20'></div>
<div class='publication parent12 parent42 parent91'></div>
<div class='publication parent20'></div>
<div class='publication parent32 parent23'></div>
I need a function that takes a class passed to it as a variable, sets they style of all divs with publication class to none and then sets tags with the specified class.
function swap_pub(pub){
document.getElementById("publication").style.display = "none";
//set style.display = "block" to all elements with class = pub
}
any thoughts on how I would do this.
Use getElementsByClassName()MDN
var pubs = document.getElementsByClassName('publication'); // a NodeList
for (var i = 0; i < pubs.length; i++) {
pubs[i].style.display = 'block';
}
This is how it looks using jQuery:
$('.publication').show(); // concise
There is also querySelectorAll which is slightly more widely supported than getElementsByClassName.
function setDisplay(className, display) {
var items = document.querySelectorAll('.' + className);
var i = items.length;
while (i--) {
items[i].style.display = display;
}
}

Categories