Remove / Replace class with another class without having an ID - Javascript only - javascript

Basicly i have two buttons one who will create divs with the class "TargetDummy" and another who should be able to remove the created "TargetDummy".
The problem is i cant seem to edit the "TargetDummy"divs since they don't have an ID and i can't give them one since there are several of them.
I am looking for a solution in javascript only. My code for creating the "TargetDummy"divs is below
var Div = document.createElement("div");
document.body.appendChild(Div).className = "TargetDummy";
I thought something like
var Dummies = document.getElementsByClassName("TargetDummy");
Dummies.className = "something";
or
Dummies.remove();
would do it, but unfortunately not. I am still learning Javascript so go easy on me :)

If you want to simply hide the Divs, you could loop through them and give them a new class via the className property.
Example JS:
var Dummies = document.getElementsByClassName("red");
function addNewClass() {
for(var i = 0; i < Dummies.length; i++) {
Dummies[i].className = "newClass";
Dummies[i--].className = "newClass"
}
}
http://codepen.io/anon/pen/OPZNJN

Related

Material Components Web - mdc attachTo only apply to the first element

I'm using Material Components Web to create a website. I have a list of button with the class .mdc-button and I activated it with the following line into my Javascript File.
window.button = new mdc.ripple.MDCRipple.attachTo(document.querySelector('.mdc-button'));
The problem is that this only applies to the first element with the class .mdc-button
Why is that and how to fix it?
document.querySelector will always return the first instance of the element found within the DOM. You can use document.getElementsByClassName('mdc-button') to return a full list of classes within the DOM.
https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
Perhaps something like this
var x = document.getElementsByClassName('mdc-button');
var i;
for (i = 0; i < x.length; i++) {
mdc.ripple.MDCRipple.attachTo(x[i]);
}
Here is an ES6 way of doing the same thing (for anyone else reading this post):
const buttons = document.querySelectorAll('.mdc-button');
buttons.forEach(button => MDCRipple.attachTo(button));

Giving a different id to each child of an element

First question ever, new to programming. I'll try to be as concise as possible.
What I want to do is to create a bunch of children inside a selected div and give each of them specific html content (from a predefined array) and a different id to each child.
I created this loop for the effect:
Game.showOptions = function() {
var i = 0;
Game.choiceElement.html("");
for (i=0; i<Game.event[Game.state].options.length; i++) {
Game.choiceElement.append(Game.event[Game.state].options[i].response);
Game.choiceElement.children()[i].attr("id","choice1");
}
};
Using the predefined values of an array:
Game.event[0] = { text: "Hello, welcome.",
options: [{response: "<a><p>1. Um, hello...</p></a>"},
{response: "<a><p>2. How are you?</p></a>"}]
};
This method does not seem to be working, because the loop stops running after only one iteration. I sincerely have no idea why. If there is a completely different way of getting what I need, I'm all ears.
If I define the id attribute of each individual p inside the array, it works, but I want to avoid that.
The idea is creating a fully functional algorithm for dialogue choices (text-based rpg style) that would work with a predefined array.
Thanks in advance.
The problem with your loop as I see it could be in a couple different places. Here are three things you should check for, and that I am assuming you have but just didn't show us...
Is Game defined as an object?
var Game = {};
Is event defined as an array?
Game.event = new Array();
Is Game.state returning a number, and the appropriate number at that? I imagine this would be a little more dynamic then I have written here, but hopefully you'll get the idea.
Game.state = 0;
Now assuming all of the above is working properly...
Use eq(i) instead of [i].
for (var i = 0; i<Game.event[Game.state].options.length; i++) {
Game.choiceElement.append(Game.event[Game.state].options[i].response);
Game.choiceElement.children().eq(i).attr("id","choice" + (i + 1));
}
Here is the JSFiddle.

Prepend some innerHTML to a div in Native Javascript

Please bear with me on this question; I have only recently started coding in Javascript and for this reason I would like a strong foundation before breaking into jQuery.
I have the following Javascript code:
var app = {
text: document.getElementById('text'),
output: document.getElementById('output'),
createDiv: document.createElement('div')
};
function postData(){
app.output[0].appendChild(app.createDiv.firstChild);
app.createDiv.classname = 'text';
document.getElementsByClassName('username').innerHTML += app.text.value;
}
onClick I want the value of app.text to print (using innerHTML) ABOVE the output div. Any ideas or questions? Sorry if I am being vague or not making sense, I have been staring at this for 4 hours now and am probably just burned out!
You'll have to create a text node and insert it before each element in the NodeList returned by document.getElementsByClassName:
var node = document.createTextNode(app.text.value);
var elements = document.getElementsByClassName('username');
for (var i = 0; i < elements.length; i++) {
var elem = elements[i];
elem.parentNode.insertBefore(node.cloneNode(), elem)
}
And just to tempt you with the jQuery version:
$('.username').before(app.text.value);
I'm not sure what you're asking, but I see the following problems with your code:
app.output[0]: there should be no [0], app.output is already an element (you got it by id). So use app.output.appendChild(app.createDiv.firstChild);. Still, this makes no sense; as Barmar said, you just created that div, so it doesn't have any children at that point.
app.createDiv.classname: should be className
document.getElementsByClassName('username').innerHTML: this returns multiple elements, maybe you want document.getElementsByClassName('username')[0].innerHTML?

Why doesn't this javascript work assign .cells[] properly?

Why doesn't this work?
var row = document.getElementById(currentRow);
var otherRow = document.getElementById(targetRow);
row.cells[0] = otherRow.cells[0];
This works with
row.cells[0].innerHTML = otherRow.cells[0].innerHTML;
However, there are attributes attached to the cell which I also want to move over without having to manually recreate them.
Solution (Note: more is being done in my actual implementation, but this is the framework):
for (var i = 0; i < 4; i++) {
var copyTo = row.cells[i];
var copyFrom = otherRow.cells[i].cloneNode(true);
copyTo.parentNode.replaceChild(copyFrom, copyTo);
}
You should be able to use cloneNode() to actually clone the node and its attributes.
Each entry in cells refers to a DOMElement. When you typed row.cells[0] = otherRow.cells[0], you are saying that you want row.cell[0] to reference the same DOMElement as otherRow.cells[0].
I'm guessing you want row.cells[0] to have the same text or HTML as otherRow.cells[0]; in which case, the second code snippet will do just that, since you are actually modifying the DOMElement, and not just changing which DOMElement you are referencing.

How do I write a mouse down event in JavaScript?

This is very basic I'm sure to JavaScript but I am having a hard time so any help would be appreciated.
I want to call a function within a for loop using the mouseDown event occurring within an object's second child node. The part italicized is my attempt to do this. The swapFE function is still a work in progress by the way. And one more thing is when I put the italicized part in the swapFE function everything works properly but when I put it in the for loop it doesn't all show up. I don't know why. I am basically trying to swap French phrases for English ones when I click the phrase with my mouse.
function setUpTranslation() {
var phrases = document.getElementsByTagName("p");
var swapFE = document.getElementsByTagName("phrase");
for (i = 0; i<phrases.length; i++) {
phrases[i].number = i;
phrases[i].childNodes[1].innerHTML = french[i];
*phrases[i].childNodes[1].onMouseDown = swapFE;*
}
}
/* see "function_swapFE(phrase,phrasenum);" below. The expression to call function swapFE
is located underneath "function swapFE(e)" because although the directions said to put the
"run swapFE" within the for loop it did not work properly that's why I put it beneath the
"function swapFE(e)".*/
function swapFE(e) {
var phrase = eventSource(e);
var phasenum = parseInt(1) = [1].innercontent.previousSibling;
phrase.node.previousSibling.onmousedown=swapFE
function_swapFE(e)(phrase,phrasenum);
}
}
If you have questions let me know.
Thanks for your help.
With this, you are creating a local variable named swapFE;
var swapFE =
document.getElementsByTagName("phrase");
Then with this you are setting this var as a mouseDown
phrases[i].childNodes[1].onMouseDown =
swapFE;*
That's not right... onMouseDown should be set to a function name, not a local variable of that name. So you should probably rename the local var to something else. That will at least get you closer to a solution.
I can only make a couple of guesses at what might be failing with your source code. Firstly, the following code assumes that all <p> tags have at least 2 child elements:
for (i = 0; i<phrases.length; i++) {
phrases[i].number = i;
phrases[i].childNodes[1].innerHTML = french[i];
*phrases[i].childNodes[1].onMouseDown = swapFE;*
}
If any <p> tags on your page have less than 2 child elements, an error will be thrown and script execution will halt. The best solution for this would be to add a class attribute to each <p> tag that will contain the elements you're looking for. Alternatively, you could just check for the existence of the second childnode with an if statement. Or you could do both.
Secondly, like all events, onmousedown should be declared in lowercase. Setting onMouseDown will not throw an error, but instead create a custom property on the element instead of attaching an event handler.
Finally, the following code:
var swapFE = document.getElementsByTagName("phrase");
will locally override the global function swapFE for that function, replacing it with a variable instead.
This is how I might write your setupTranslation function:
function setUpTranslation() {
var phrases = document.getElementsByTagName("p");
// rename the swapFE var as outlined below
var swapFENodes = document.getElementsByTagName("phrase");
var cNode; // set up an empty variable that we use inside the loop
for (i = 0; i<phrases.length; i++) {
/* Check for the existence of the translationPhrase class
in the <p> tag and the set the cNode var to childNodes[1]
and testing for its existence at the same time */
if (cNode.className != "translationPhrase"
|| !(cNode = phrases[i].childNodes[1]))
continue; // skip to the next iteration
phrases[i].number = i;
cNode.innerHTML = french[i];
cNode.onmousedown = swapFE; // Changed onMouseDown to onmousedown
}
}

Categories

Resources