Javascript changing a specific element in a div - javascript

So I have something like this in my html:
<div id="basket">
<div id="item">Apple</div>
</div>
<div id="basket">
<div id="item">Orange</div>
</div>
<div id="basket">
<div id="item">Banana</div>
</div>
// And so on
How would I be able to change the innerHTML of each 'item' div individually?
For example, how would I change the div that says 'banana' to something else?

As already mentioned within the comments, an ID has to be unique so you have to change them to classes.
Then to solve your issue, you can use querySelectorAll to select all elements with the class item. Then you sue the forEach-loop and check the innerHTML of every Element. if it matches "Banana" you can rewrite the innerHTML (should use textContent though for security reasons):
document.querySelectorAll('.item').forEach(el => {
if (el.textContent == 'Banana') {
el.textContent = 'The Minions ate the Banana';
}
})
<div class="basket">
<div class="item">Apple</div>
</div>
<div class="basket">
<div class="item">Orange</div>
</div>
<div class="basket">
<div class="item">Banana</div>
</div>

Related

Change HTML innerText in element with duplicates

I want to specifically change the innerText of the "quantity" div from this HTML:
<div class="shop" id="shop">
<div id="1" class="item"> // Div nr. 1
<div class="details">
<div class="buttons">
<div id="1" class="quantity"> // <-- Don't change this one!
</div>
</div>
</div>
<div id="2" class="item"> // Div nr. 2
<div class="details">
<div class="buttons">
<div id="2" class="quantity"> // <-- Change this one!
</div>
</div>
</div>
</div>
I tried using document.querySelector('.quantity').innerText = "". But that only changes the first occurring div with the class "quantity", which is within "Div nr. 1".
How do I specifically target the "quantity" class within "Div nr. 2"?
Given the html you provided, you can select the second .item and then descend to its .details like so:
document.querySelector('.item:nth-child(2) .quantity').innerText="";
https://jsfiddle.net/6L8gntmh/
It would be wise to make the id`s unique if you have access to the html. Then you would be able to select by their id.
You can use querySelectorAll this allows you to modify HTML elements based on class and id not just one of each.
document.querySelectorAll('.quantity')[1].innerText = "my text"
Depending on your specific situation, it might be more useful to use a different type of selector:
document.querySelector('#id2 .quantity').innerText = ""
All ids must be unique and can start with a number, but it's a pain to select, I would recommend starting your id with a letter instead.

How to change all classname elements of specific classname

How to change all classname elements of specific classname?
I mean, let's say I have 3 divs with classes "MyClass", and i want to change their classnames to "notMyClass" in JavaScript, how to do it?
<div class="MyClass">
</div>
<div class="MyClass">
</div>
<div class="MyClass">
</div>
<!--TO-->
<div class="notMyClass">
</div>
<div class="notMyClass">
</div>
<div class="notMyClass">
</div>
I know that it's very easy by calling element by it's id, but how to do it by it's classname?
Select all elements with the MyClass class with querySelectorAll, then loop through each element (with NodeList.forEach) and use classList.replace:
document.querySelectorAll('.MyClass').forEach(e => e.classList.replace('MyClass', 'notMyClass'))
.notMyClass{
background-color:green;
}
<div class="MyClass">A</div><div class="MyClass">B</div><div class="MyClass">C</div>
<!--TO-->
<div class="notMyClass">D</div><div class="notMyClass">E</div><div class="notMyClass">F</div>
Use querySelectorAll method:
Array.from(document.querySelectorAll('.MyClass')).forEach(elem => {
elem.className = 'otherClass';
});
Note that I used Array.from, because querySelectorAll returns a NodeList, not an array.

FadeOut all id's with the same name

This is my HTML:
<div class="content-box" id="enabled_add">
<h2 class="title">hallo</h2>
<div class="content-box-heading-orange"></div>
<div class="content-box-content">
Hallo
</div>
</div>
<div class="content-box" id="enabled_add">
<h2 class="title">hallo2</h2>
<div class="content-box-heading-orange"></div>
<div class="content-box-content">
Hallo2
</div>
</div>
This is my JS
$('#usernav_close').click(function(){
setTimeout(function(){
$('#enabled_add').fadeOut('slow');
});
});
I want to get all of the content-boxes with the id enabled_add to FadeOut.
But my problem is that only the first element is selected.
ids must be unique. If you try to reuse an id, only the first will be found/updated by jQuery. You want to use a class here.
<div class="content-box enabled_add">
<h2 class="title">hallo</h2>
<div class="content-box-heading-orange"></div>
<div class="content-box-content">
Hallo
</div>
</div>
<div class="content-box enabled_add">
<h2 class="title">hallo2</h2>
<div class="content-box-heading-orange"></div>
<div class="content-box-content">
Hallo2
</div>
</div>
$('#usernav_close').click(function(){
setTimeout(function(){
$('.enabled_add').fadeOut('slow');
});
});
The id attribute is supposed to be unique to an element on a page. You aren't supposed to use the same id twice in one document.
The difference between ids and classes
You can however give an element more than one class.
<div class="content-box enabled_add">
That would mean your selector would read
$('.enabled_add')

How can I select a parent element, and all child divs that are not the first, as well as siblings of the parents and their children

Sorry for the poor title, I'm not sure how to word this issue.
I need some help writing a jQuery or javascript selector to get every childBlock that isn't the first. There are N number of parentBlock divs with at least one childBlock div child. We would like to change some of the labels for every subsequent child div after the first. What is the most efficient way to select these elements?
<div class="parentBlock">
<div class="elementHead">
</div>
<div class="elementBody">
<div class="childBlocks">
<div class="childBlock" id='1'>
</div>
<div class="childBlock" id='2'>
</div>
<div class="childBlock" id='3'>
</div>
<div class="childBlock" id='4'>
</div>
...
</div>
</div>
<div>
<div class="parentBlock">
<div class="elementHead">
</div>
<div class="elementBody">
<div class="childBlocks">
<div class="childBlock" id='5'>
</div>
<div class="childBlock" id='6'>
</div>
<div class="childBlock" id='7'>
</div>
<div class="childBlock" id='8'>
</div>
...
</div>
</div>
<div>
So in the example above, I would like to select childBlocks with an id of 2, 3, 4, 6, 7, 8. In my actual code, these div's don't have an id, they are just classed if that makes a difference at all.
I've tried:
$(".parentBlock").find(".childBlock").not(':first').find('label.category ').text("Subcategory");
But it seems to find the first childBlock on the screen, skip over it, then apply the text change to every other childBlock div that it finds.
Thoughts, or suggestions?
You were very close. You want first-child, not first:
http://jsfiddle.net/pMYWS/
$(".parentBlock").find(".childBlock").not(':first-child').text("Subcategory");
(I am assuming that label.category is something present in your real code that isn't shown in this demo snippet)
what about something like this?
$(".childBlocks:not(:first-child)") (do something here)

Get elements just 1 level below the current element by javascript

I need to access the DOM tree and get the elements just 1 level below the current element.
Read the following code:
<div id="node">
<div id="a">
<div id="aa">
<div id="ab">
<div id="aba"></div>
</div>
</div>
</div>
<div id="b">
<div id="ba">
<div id="bb">
<div id="bba"></div>
</div>
</div>
</div>
<div id="c">
<div id="ca">
<div id="cb">
<div id="cba"></div>
</div>
</div>
</div>
</div>
I want to get the 3 elements "a", "b", "c" under "node". What should I do?
var nodes = node.getElementsByTagName("div") <---- I get all the divs but not the 3 divs I need.
var nodes = node.childNodes; <---- works in IE, but FF contains Text Node
Does anyone know how to solve the problem?
You could use a function that rules out all non-element nodes:
function getChildNodes(node) {
var children = new Array();
for(var child in node.childNodes) {
if(node.childNodes[child].nodeType == 1) {
children.push(child);
}
}
return children;
}
I'd highly recommend you look at JQuery. The task you're looking to do is straightforward in pure Javascript, but if you're doing any additional DOM traversal, JQuery is going to save you countless hours of frustration. Not only that but it works across all browsers and has a very good "document ready" method.
Your problem solved with JQuery looks like:
$(document).ready(function() {
var children = $("#node").children();
});
It looks for any element with an id of "node" then returns its children. In this case, children is a JQuery collection that can be iterated over using a for loop. Additionally you could iterate over them using the each() command.
This is simplier than you think:
var nodes = node.querySelector("node > div");
Try this (late answer, but can be useful for others):
var list;
list=document.getElementById("node").querySelectorAll("#node>div");
Universal selectors can do the trick:
var subNodes = document.querySelectorAll("#node > *");
Query parts:
#node is unique container selector
> next slector should be applied only on childs
* universal selector that match every tag but not text
Can I use universal selector
In my opinion the easiest way to do this is to add a class name to the
first level child nodes:
<div id="node">
<div id="a" class="level_1">
<div id="aa">
<div id="ab">
<div id="aba"></div>
</div>
</div>
</div>
<div id="b" class="level_1">
<div id="ba">
<div id="bb">
<div id="bba"></div>
</div>
</div>
</div>
<div id="c" class="level_1">
<div id="ca">
<div id="cb">
<div id="cba"></div>
</div>
</div>
</div>
</div>
and then to use the method getElementsByClassName, so in this case:
document.getElementById('node').getElementsByClassName('level_1');
I think node.childNodes is the right place to start. You could (to make it work with FF too), test the nodeName (and possibly nodeType) of all child nodes you get, to skip text nodes.
Also you might have a look at some javascript library like prototype, which provide a lot of useful functions.
I've added some text so we can see that it is working, and JavaScript that will add "added!" to the bottom of each of the divs at the base:
var cDiv = document.querySelectorAll('body > div > div'), i;
for (i = 0; i < cDiv.length; i++)
{
cDiv[i].appendChild(document.createTextNode('added!'));
}
<div id="node">
<div id="a">a
<div id="aa">aa
<div id="ab">ab
<div id="aba">aba</div>
</div>
</div>
</div>
<div id="b">b
<div id="ba">ba
<div id="bb">bb
<div id="bba">bba</div>
</div>
</div>
</div>
<div id="c">c
<div id="ca">ca
<div id="cb">cb
<div id="cba">cba</div>
</div>
</div>
</div>
</div>

Categories