I want to set the width of my object to 80%. The parent div width is 100%
whats wrong?
var howManyDivsIHave = document.querySelectorAll('#section div.divs').length;
if(howManyDivsIHave == "1"){
var divs = document.getElementById("section").getElementsByClassName("divs");
divs.style.width = "80%";
divs.style.height = "80%";
divs.style.margin = "10%";
}
else if (howManyDivsIHave == "2"){
divs.style.width = "40%";
divs.style.height = "40%";
divs.style.margin-top = "30%";
divs.style.margin-bottom = "30%";
divs.style.margin-left = "5%";
divs.style.margin-right = "5%";
}
else if (howManyDivsIHave == "3"){
divs.style.width = "40%";
divs.style.height = "40%";
divs.style.margin = "5%";
}
}
UPDATE: You're still not accessing the individual members of the result set. You need to iterate through the results of getElementsByClassName as you're still trying to set style properties on the collection of results instead of the individual results. You also need to call getElementsByClassName just after your call to querySelectorAll or your divs var is going to fall out of scope when you get to the else if blocks. You should be able to figure out how to structure your loops from the original answer, so I'll leave it unedited:
childNodes is an Array. You need to iterate through the array and set your styles on each individual element. In the code you posted you're setting the styles on the array, not the individual DOM elements. Try something like
var divs = document.getElementById("section").childNodes;
for (var i = 0; i < divs.length; i++)
{
divs[i].style.width = "80%";
divs[i].style.height = "80%";
divs[i].style.margin = "10%";
}
Note that childNodes will contain all the children of your DOM element with an id of "section", so if there are other children that aren't divs under the "section" DOM element that you don't want to apply this styling to, you're going to need to do further filtering.
childNodes is a NodeList or array. You need to iterate through and add that style to the individual items:
for(i=0;i<divs.length;i++){
divs[i].style.width = "80%";
divs[i].style.height = "80%";
divs[i].style.margin = "10%";
}
Related
My requirement is to update the dynamic content to the child element. I tried to iterate the parent elements one by one and trying to update the child elements but I am unable can anyone guide me please?Thanks
<section id="parent_sec">
<div id="parent1">
<div id="childdiv">default1</div>
</div>
I tried like belo
function getTragetElement(elem, tem){
var tem1 = 'childiv';
for (i = 0; i <= elem.length - 1; i++) {
if(elem[i].childdiv!= undefined && elem[i].childdiv!= null){
elem[i].childdiv.innerHTML = "12345";
break;
}else{
getTragetElement(elem[i], tem1);
}
}
}
var parentDiv = document.getElementById("parent_sec");
var childElements = parentDiv.children;
getTragetElement(childElements[0], 'childdiv')
first when you pass in the array as a parameter don't declare an index value just pass in the array and let only the function declare the value (as your function is already doing).
And also take out the .childdiv when changing the content of the child div, because this doesn't work and there is no need for calling the child div, because the array with the index declaration, in your case - elem[i] - already contains the child div itself.
so here is a edited example:
function getTragetElement(elem, tem){
var tem1 = 'childiv';
for (i = 0; i <= elem.length ; i++) {
if(elem[i]!= undefined && elem[i] != null){
elem[i].innerHTML = "12345";
}else{
getTragetElement(elem[i], tem1);
}
}
}
var parentDiv = document.getElementById("parent1");
var childElements = parentDiv.children;
//passing in the array childElenents without an index value
getTragetElement(childElements, 'childdiv')
So by using native javascript, how would I go about saying
"if this object has this css class, add this to the title attribute"
document.addEventListener("DOMContentLoaded", function(event) {
if(element.classlist.contains("current_page_item")||element.classlist.contains("current-page-ancestor")){
}
});
That is as far as I've gotten, I'm trying to stick to native javascript just so we don't have to load up any libraries and can keep the site as minimalist as possible.
You can use getElementsByClassName()
var x = document.getElementsByClassName("current_page_item");
Then loop and add title
x.forEach(function(element){
element.title = "title";
});
or
for (var i = 0; i < x.length; i++) {
x[i].title ="title";
}
To answer to your comment, to apply the title to the "a" element that is a child of the div element that has the "current_page_item" class
for (var i = 0; i < x.length; i++) {
var y = x[i].getElementsByTagName("a");
y[0].title = "title";
}
Similar to Rohit Shetty's reply, you could also use the querySelector:
let elements = document.querySelector(".current_page_item");
elements.forEach(function(e) {
e.title = "title";
);
You can use getElementsByClassName()
var x = document.getElementsByClassName("current_page_item");
for(var i=0;i<x.length;i++){
x[i].title += "BLAH";
}
I don't now if I have understood well.
But let's try.
First, locate the elements.
const nodes = document.querySelectorAll('.current_page_item, .current_page_item')
// nodes are the elements of one of the classes names
Then, apply the class Names to title.
function containsOfTheClasses (node) {
return classNames.some(x => node.classList.contains(x))
}
nodes.forEach(function (node) {
node.title += classNames.filter(containsOfTheClasses).join(' ')
})
I am building a Todo-List Project and i am stuck at looping through my newly created list items.
This is what i am doing:
Created an array.
Made li items for array's each element through looping so that array appears in a list manner.
And then looping through newly created li section to addEventListener on each of li's ( But this one is not working).
var arrList = ["play","learn","walk"];
var list = document.querySelectorAll("li");
var done = false;
//printing array in list manner
for(let i = 0; i < arrList.length; i++){
let el = document.createElement("li")
el.textContent = arrList[i];
document.querySelector("ul").appendChild(el);
}
//looping through each li's to apply if else statement
for(let i = 0; i < list.length; i++){
list[i].addEventListener("click",function(){
if(!done){
this.style.textDecoration = "line-through";
done = true;
}else{
this.style.textDecoration = "none";
done = false;
}
})
}
You're code is mostly correct, however there are a few issues that need to be addressed. First, consider replacing your for loop with iteration based on forEach() as shown below. Using forEach() in this way allows you to leverage "closure" which in this case will greatly simplify your code. For instance, you can use the closure feature to store the done state of each item in your list, rather than storing that state explicitly in an array.
The other issue I noticed was var list = document.querySelectorAll("li"); queries the document for li elements before any are added to your document - later in your script it seems you're iterating that empty query result and expecting it to contain the added li elements.
Here's a working snippet - hope this helps!
var arrList = ["play", "learn", "walk"];
// Iterate the list via forEach
arrList.forEach(function(arrItem) {
// We're now in a new "closure" for this list item
// so we can define some state like "done" that will
// be used exclusively for this list item
var done = false;
// Create li element for this list item as before
var el = document.createElement("li")
el.textContent = arrItem;
// Configure click event
el.addEventListener("click", function() {
// Notice we're able to use the done variable
// in this closure for this list item? The key
// thing to understand is that each list item
// will have it's own unique "done" variable
if (!done) {
el.style.textDecoration = "line-through";
done = true;
} else {
el.style.textDecoration = "none";
done = false;
}
})
document.querySelector("ul").appendChild(el);
});
<ul></ul>
It seems like you only have one done variable that is shared for every item on the todo list. Therefore if you click one of the items all of the items will be crossed out. You will need a boolean variable for every item in your to do list.
Add this line just above the second for loop and remove from the top.
var list = document.querySelectorAll("li");
You are assigning list the values even before they are created.
from the source code I see that the list li item is initialized before new li item been created,
it will cause the list li item not contains the new one,
due to that addEventListener will not working for the new item.
to fix this, just need move init list li item code after creation part :
var arrList = ["play","learn","walk"];
var done = false;
//printing array in list manner
for(let i = 0; i < arrList.length; i++){
let el = document.createElement("li")
el.textContent = arrList[i];
document.querySelector("ul").appendChild(el);
}
var list = document.querySelectorAll("li");
//looping through each li's to apply if else statement
for(let i = 0; i < list.length; i++){
list[i].addEventListener("click",function(){
if(!done){
this.style.textDecoration = "line-through";
done = true;
}else{
this.style.textDecoration = "none";
done = false;
}
})
}
Please, be simple...
var
arrList = ["play","learn","walk"],
UL_arrList = document.querySelector("ul")
;
arrList.forEach (arrItem => {
let el = document.createElement("li");
el.textContent = arrItem;
UL_arrList.appendChild(el);
el.onclick = function(e){
let deco = this.style.textDecoration || 'none';
this.style.textDecoration = (deco==='none') ? 'line-through': 'none';
}
});
<ul></ul>
I'm trying to change the lay-out for WooCommerce, but since I can't get that working I decided to change it to my wishes by using Javascript to create a div and append it to the existing div. I do have some lines that go through every div with a certain class, but that only works when I let them change the innerHTML. But when I use appendChild, it only appends to the last div. Anyone have an idea what could be it? This is the code I use. The class "product-type-simple" is the div that already exists.
var product_item_wrapper = document.createElement("div");
product_item_wrapper.style.width = "100px";
product_item_wrapper.style.height = "100px";
product_item_wrapper.style.background = "red";
product_item_wrapper.style.color = "white";
product_item_wrapper.innerHTML = "Hello";
product_item_wrapper.className = "product";
var divjes = document.getElementsByClassName("product-type-simple");
for(var i = 0; i < divjes.length; i++){
divjes[i].appendChild(product_item_wrapper);
}
You are creating one element. Then you append it as a child of multiple elements. Each time you do, you remove it from where it was before and place it in the new element.
If you want multiple elements, then you need to create multiple elements.
Move the first 7 lines of your code so they are inside the loop.
One element can only be appended to a single div. Consider making a function which returns a new element to be appended:
function createWrapper()
{
var product_item_wrapper = document.createElement("div");
product_item_wrapper.style.width = "100px";
product_item_wrapper.style.height = "100px";
product_item_wrapper.style.background = "red";
product_item_wrapper.style.color = "white";
product_item_wrapper.innerHTML = "Hello";
product_item_wrapper.className = "product";
return product_item_wrapper;
}
var divjes = {};
divjes = document.getElementsByClassName("product-type-simple");
for (var i = 0; i < divjes.length; i++)
{
divjes[i].appendChild(createWrapper());
}
I'm writing a javascript function where I get a ul object from my HTML and want to set the text of one of the li elements in theul`. I'm doing:
list = document.getElementById('list_name');
Then I want to access the ith li element of list using a loop.
I have:
for (i = 0; i < 5; i++) {
list[i].innerHTML = "<a>text</a>";
}
but this is not working. What is the proper way to do it?
You need to access the child li elements of the ul. JavaScript and the DOM API can't automagically do that for you.
var list = document.getElementById('list_name'),
items = list.childNodes;
for (var i = 0, length = childNodes.length; i < length; i++)
{
if (items[i].nodeType != 1) {
continue;
}
items[i].innerHTML = "<a>text</a>";
}
You could also use getElementsByTagName('li') but it will get all descendent li elements, and it seems you want only the direct descendants.
You could also avoid innerHTML if you want.
var a = document.createElement('a'),
text = document.createTextNode('text');
a.appendChild(text);
items[i].appendChild(a);
innerHTML can cause issues, such as lost event handlers and the performance issue of serialising and re-parsing the HTML structure. This should be negligible in your example, however.
jQuery Sample code, although the others work:
$("#list_name li").text("<a href=''>text</a>");
Its much more succinct with jQuery
You can try the following
var el = document.createElement("li"),
content = document.createTextNode("My sample text"),
myUl = document.getElementById("ulOne");
el.appendChild(content);
el.id = "bar";
myUl.appendChild(el);
Here's the demo: http://jsfiddle.net/x32j00h5/
I prefer a aproach using getElemenetByTagName, if somehow you get a extra node like a script tag or a span you will have problems. A guess this code will help you:
var list = document.getElementById("mylist");
var items = list.getElementsByTagName("li");
for(var i = 0, size = items.length; i< size; i++){
items[i].innerHTML = "<a href='#'>LINK</a>";
}