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

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));

Related

How to clone html elements from array to new parent element

I've got a task to do - to do list. I have a problem because i don't know how to move elements from parent "priority" to parent "standard".
My code of button to move is:
moveToStandardButton.addEventListener('click', function() {
const allListElements = document.querySelectorAll('[data-id="move"]');
for (let i = 0; i < allListElements.length; i++) {
let toClone = allListElements[i].checked;
}
})
toClone shoud have all list elements which are checked by user and then after click button it should move this elements to parent "standard". I've tried to do it like this but i can't use cloneNode at toClone or toClone[i].
If you log toClone, it is probably a boolean (true or false), as it is pulling whether the element is checked.
Try the following:
moveToStandardButton.addEventListener('click', function() {
// Get all elements that have a data-id of move
// I'm assuming these elements are the ones that need to move ;)
const allListElements = document.querySelectorAll('[data-id="move"]');
// iterate through the elements that need to move
for (let i = 0; i < allListElements.length; i++) {
let toClone = allListElements[i]; // Note that 'checked' isn't involved
if(!toClone.checked) continue; // If the element isn't checked, move to next element.
const clonedEl = toClone.cloneNode(true);
document.querySelector('#myOtherList').appendChild(clonedEl);
}
})
So after reading your question, I would recommend you watch or read some guides on JavaScript. You have some glaring issues that will become very apparent once you spend some time learning.
That said, I can lend some help to point you in the right direction.
1) It is not recommended to use data attributes as element identifiers. I would instead use a class, rather than data-id="move"
2) Your line let toClone is defined inside the for loop, and is scoped as such. It will not be available outside of the for loop.
3) Try creating an array outside of your for loop, and storing each checked element inside of it, and then operating on them after your loop.

What is a safe alternative to .innerHTML and Jquery .append?

Firefox addon got removed because of unsafe assignment to innerHTML. Replaced it with the Jquery append(), but it is also unsafe. What can I use instead?
I need to add content dynamically to the extension's DOM. Mozilla gave me this link when they took down the addon: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Safely_inserting_external_content_into_a_page
But I can not figure out from the link how to add nodes to an existing node in a safe way.
This is an example of what i'm doing now. I have several places where I append a node to another node. In this case I need to make a div for every category and add it to the node "folders"
var folders = $("#folders");
for (var i = 0; i < categories.length; i++) {
var s = categories[i];
var categoryFolder = $("<div>");
categoryFolder.addClass("folder");
categoryFolder.attr("id",s);
categoryFolder.text(s);
folders.append(categoryFolder);
}

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

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

Displaying all icons in a glyph

I'm writing a widget UI where the user can manipulate widgets and text. One of the UI functions needed is to select an icon from the list of icons in a glyph and as I'm using twitter bootstrap it should be possible to select the "icon-" classes in the CSS in JavaScript then display them in a DIV. However I'm still relatively new to web development so unsure how I can loop through all the CSS classes selecting all the "icon-" classes. I can see how to do that with a selector to search the HTML body, for example with $.find("[class^='icon-']"); but I'm not sure how to do similar to search the CSS file itself and extract a list of CSS icon classes.
Thanks for any pointers.
Something like this should work if your browser implements the CSSStyleSheet interface:
var icons = [];
var cssRules = document.styleSheets[0].cssRules; // your bootstrap.css
for (var i=0; i<cssRules.length; i++) {
var selectorText = cssRules[i].selectorText;
if (selectorText && selectorText.match(/^\.icon-[a-z_-]+$/)) {
icons.push(selectorText);
}
}
http://jsfiddle.net/V2wjX/
The best approach I can think of is creating an array of the possible values, then looping through them. Here, I made it for you: (from this page)
var icons = ["glass","music","search","envelope","heart","star","star-empty","user","film","th-large","th","th-list","ok","remove","zoom-in","zoom-out","off","signal","cog","trash","home","file","time","road","download-alt","download","upload","inbox","play-circle","repeat","refresh","list-alt","lock","flag","headphones","volume-off","volume-down","volume-up","qrcode","barcode","tag","tags","book","bookmark","print","camera","font","bold","italic","text-height","text-width","align-left","align-center","align-right","align-justify","list","indent-left","indent-right","facetime-video","picture","pencil","map-marker","adjust","tint","edit","share","check","move","step-backward","fast-backward","backward","play","pause","stop","forward","fast-forward","step-forward","eject","chevron-left","chevron-right","plus-sign","minus-sign","remove-sign","ok-sign","question-sign","info-sign","screenshot","remove-circle","ok-circle","ban-circle","arrow-left","arrow-right","arrow-up","arrow-down","share-alt","resize-full","resize-small","plus","minus","asterisk","exclamation-sign","gift","leaf","fire","eye-open","eye-close","warning-sign","plane","calendar","random","comment","magnet","chevron-up","chevron-down","retweet","shopping-cart","folder-close","folder-open","resize-vertical","resize-horizontal","hdd","bullhorn","bell","certificate","thumbs-up","thumbs-down","hand-right","hand-left","hand-up","hand-down","circle-arrow-right","circle-arrow-left","circle-arrow-up","circle-arrow-down","globe","wrench","tasks","filter","briefcase","fullscreen"]
Now you can loop through this array, and create the elements as needed.
for (var i=0,l=icons.length; i<l; i++){
var el = document.createElement('i');
el.className = 'icon-'+icons[i];
document.getElementById("iconContainer").appendChild(el);
}
JSFIDDLE
As for searching the CSS, I can suggest you to write a function like this:
You somehow get the contents of a CSS file into a string, using AJAX (jqXHR) possibly.
Then, write a very basic parsing script, which accepts the CSS string as the parameter.
function getIcons(cssStr){
var matches = cssStr.match(/\.icon\-\w*.*\{/g), icons = [];
for (var i=0,l=matches.length; i<l; i++) icons.push(matches[i].replace(/\.icon\-/g,'').replace(/\W/g,''));
return icons;
}
This will give you the array shown before.
JSFIDDLE

Executing a function to each item on a Nodelist in Javascript

I want to add an <img> to every <td> tag with a certain CSS Class in my page.
I used "querySelectorAll" to look them up, like this:
var painted = document.querySelectorAll('.painted');
Now I would like to add to each one of them a specific image with a unique ID. I assume I need to loop through the list somehow and edit each element's innerHTML, could anyone provide the syntax for that?
Thanks
Just run it like a normal for loop, and add properties to each element.
for (var i = 0, len = painted.length; i < len; i++) {
painted[i].id = "foo" + i;
painted[i].innerHTML = "<strong>Your content</strong>";
}
This uses innerHTML to create new content. If you need more complex content processing then there's no single syntax. You need to learn the DOM API and perform the needed manipulations.
For example, if you wanted to add an image, you can create one and append it directly.
for (var i = 0, len = painted.length; i < len; i++) {
var img = document.createElement("img");
img.id = "myimage" + i;
painted[i].appendChild(img);
}
Notice that I'm not using HTML markup. A DOM node doesn't have "HTML content". It is part of an object tree structure, so it has child nodes, which have their own child nodes, and so on.
So what you need to do, is perform some DOM selection with the current painted element as the root, and decide what should go where.

Categories

Resources