How access second div with same id using querySelectorAll javascript? - javascript

Here, I have two div on my webpage both div have almost same data.
accept type attribute.
My first div attribute have type="timeline".
and Second div attribute type ="slideshow".
When my page load it only detects the first div.
But I have a condition if my div type equal to slideshow then my code run but it detects only first div.
Here is my code.
<div type='timeline' id='slide'>
<section>
<header>Title One</header>
<article>Content</article>
</section>
<section>
<header>Title Two</header>
<article>Content</article>
</section>
<section>
<header>Title Three</header>
<article>Content</article>
</section>
<section>
<header>Title Four</header>
<article>Content</article>
</section>
</div>
var divSlide = document.querySelectorAll('#slide');
var myNodeList = divSlide.length;
for(i = 0; i < myNodeList.length; i++) {
var divMain = document.getElementById("slide");
console.log(divMain);
var align = divMain.getAttribute("type");
console.log(align);
console.log(myNodeList)
if(align=='slideshow'){
console.log("my working code");
}
}
What should i do.
Help will be appreciated.

You have a few of mistakes in your code that we need to fix first.
First, you shouldn't use the same id value more than once in your code so you need to replace the id with a class (even though our code can still work with id here).
Second mistake - in your for loop you are using the wrong variable "myNodeList.length", myNodeList variable already is the length so it does not have a length property. you should instead use the divSlide variable like this:
for(i = 0; i < divSlide.length; i++)
Third mistake- in order to access the current item that is being looped over you should use the variable that holds the list (which is divSlide here)and then add to it i in brackets to indicate the current index in use, like this
var divMain = divSlide[i];
// instead of this: var divMain = document.getElementById("slide");
Fourth - you should in most cases use triple = signs to check for values. so instead of == you should use ===
this is how the code will look like finally:
var divSlide = document.querySelectorAll('#slide');
var myNodeList = divSlide.length;
document.addEventListener("DOMContentLoaded", functionName)
function functionName(){
for(i = 0; i < divSlide.length; i++) {
var divMain = divSlide[i];
var align = divMain.getAttribute("type");
if(align ==='slideshow'){
console.log("my working code");
}
}
}
and this is codepen example

You can get div by type attribute like this:
HTML
<div type='timeline' id='slide'>
this is timeline
</div>
<div type='slideshow' id='slide'>
this is slideshow
</div>
JS
$('#slide[type=slideshow]') // get div that has id='slide' and type='slideshow'
Online Demo (jsFiddle)

Related

In pure JS, I am trying to set two similar classes but with different numbers or to set the same class to two different elemnts

I tried to set the same class imagens-giratorias to two elements or to set imagens-giratorias and imagens-giratorias-2. The class worked in first element, and the same class stopped of animating in the second element.
[I provide the JSFiddle at the end.]
Check the #rafaelcastrocouto's original code at https://stackoverflow.com/a/59524483/8041366. If you prefer reading the complete code here, here is the code taken from there, but with a bit modified:
var counter = 1;
var div = document.querySelector('.imagens-giratorias');
var imagens = document.querySelectorAll('.imagens-giratorias img');
var showNext = function () {
counter++;
if (counter > 3) counter = 1;
div.classList.remove('imagem1', 'imagem2', 'imagem3')
div.classList.add('imagem'+counter);
};
for (var img of imagens) {
img.addEventListener('animationend', showNext);
}
And small CSS snippet:
<div class="section-2">
<div class="item-2">
<div class="imagens-giratorias imagem1">
</div>
</div>
</div>
<div class="section-3">
<div class="item-2">
<div class="imagens-giratorias imagem1">
</div>
</div>
Or
<div class="section-3">
<div class="item-2">
<div class="imagens-giratorias-2 imagem1">
</div>
</div>
1st solution, that same original code above I am referring.
2nd solution:
var div = document.querySelector('.imagens-giratorias, .imagens-giratorias-2');
var imagens = document.querySelectorAll('.imagens-giratorias img, .imagens-giratorias-2 img');
3rd solution
var div = document.querySelector('[class^=imagens-giratorias]');
var imagens = document.querySelectorAll('[class^=imagens-giratorias] img');
4th solution
const contador = 1;
const div = document.querySelector('.imagens-giratorias');
const imagens = document.querySelectorAll('.imagens-giratorias img');
I also tried to use from multiple selectors with document.querySelectorAll. No luck.
But all these solutions did not work.
JSFiddle
Please pay attention to two elements. While one element will always animate, another will stop of animating.
https://jsfiddle.net/gusbemacbe/mbp84u6r/2/
If I understand you correctly you're trying to grab elements that have a class name starting with imagens-giratorias. If that's the case, use the ^ attribute selector as shown below:
document.querySelectorAll("[class^="imagens-giratorias"]")
Update:
Based on your update it appears that only one of your two divs' images is animating but in reality they're stacked on top of each of other. Feel free to use whatever layout method you want but for demonstration's sake I floated one left and the other right. Other that it was a matter of looping through your divs and assigning your function to their child images as so:
var divs = document.querySelectorAll('.imagens-giratórias');
var contador = 1;
var mostrarPróximo = function(div) {
contador++;
if (contador > 3) contador = 1;
div.classList.remove('imagem1', 'imagem2', 'imagem3')
div.classList.add('imagem' + contador);
};
Array.from(divs).forEach(function(div, index) {
var images = div.querySelectorAll('img');
Array.from(images).forEach(function(img) {
img.addEventListener('animationend', mostrarPróximo.bind(null, div));
});
});
https://jsfiddle.net/1r6yjf5s/

Change only the text of an anchor javascript

I'm trying to write a simple script which will change the text of a number of anchors on a page. I'm quite new to Javascript and I'm able to change the anchors but it changes the whole tag including removing the href.
How do I edit just the text only without affecting the href?
<body>
<div class="loop-add-to-cart">
Add to basket
<div class="wpd-buttons-wrap-simple" data-id="11544">
Design from blank
</div>
</div>
<script>
function buybuttons() {
var buybuttons = document.getElementsByClassName('wpd-buttons-wrap-simple');
for(var i = 0; i < buybuttons.length; i++){
buybuttons[i].innerHTML="Test";
};
}
buybuttons();
</script>
</body>
You can use a query selector to get all a tags inside an element with a class of wpd-buttons-wrap-simple:
document.querySelectorAll('.wpd-buttons-wrap-simple a');
You can then set the textContent or innerHTML of the link.
<body>
<div class="loop-add-to-cart">
Add to basket
<div class="wpd-buttons-wrap-simple" data-id="11544">
Design from blank
</div>
</div>
<script>
function buybuttons() {
var buybuttons = document.querySelectorAll('.wpd-buttons-wrap-simple a');
for(var i = 0; i < buybuttons.length; i++){
buybuttons[i].textContent = "Test";
};
}
buybuttons();
</script>
</body>
Using 'querySelectorAll' you can get the element the class and the element inside as below:
document.querySelectorAll('.wpd-buttons-wrap-simple > a')
function buybuttons() {
var buybuttons = document.querySelectorAll('.wpd-buttons-wrap-simple a');
for(var i = 0; i < buybuttons.length; i++){
buybuttons[i].innerHTML="Test";
};
}
buybuttons();
You are currently overwriting the innerHTML of the div element, but you are looking for the anchor element inside of the div.
Use document.querySelectorAll to get all of them, or document.querySelector to only get the first.

Getting infinity loop when I append div to existing divs?

I had took some program test online,from there I got some infinity loop error in appending new div to existing div.
<div id="one">
<div id="two"></div>
</div>
And this JS code is to add new div:
appendChildren();
function appendChildren() {
var allDivs = document.getElementsByTagName("div");
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
}
I want the HTML to look like this:
<div id="one">
<div id="two">
<div></div>
</div>
<div></div>
</div>
But at run time the program doesn't stop looping. Why? I couldn't guess! So can I run that appendChildren() only one time or is there another solution?
document.getElementsByTagName("div") is a live collection - it always reflects the actual data.
It means that when you append a div item, it is automatically appended to your collection. So, it never ends.
You can copy your collection using [].slice.call so that it doesn't change.
Here is the working demo snippet:
function appendChildren() {
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
}
appendChildren();
// For demonstration purposes only:
document.getElementById('html').innerText = document.getElementById('one').outerHTML;
<div id="one">
<div id="two">
</div>
</div>
<pre id="html"></pre>
The html element displays the HTML result - however, it looks bad. You may use developer tools to see the actual structure in a familiar way.

How to remove all HTML tag by using the loop with Javascript

<div id='images'><img id='center_loadingImage' align='middle' src='loading.gif' alt='Loading Image'></div>
How to remove all <div> with the loop with Javascript?
Here is my code:
var value = document.getElementsByTagName("images");
for (var i = 0; i < value.length; i++) {
$(value[i]).remove();
}
You can only use same id value once per page. Change it to class, i.e. images
You will then have multiple div with class images and will be able to easily remove the spinners like this:
$(".images").remove();
If you have a lot of spinners, just wrap them with a div and remove the div. Something like this:
HTML:
<div id="jedi-wrapper">
<div class="images">
...
</div>
</div>
jQuery:
$("#jedi-wrapper").remove();
From the image, it looks like you are loading some values using AJAX. Why don't you remove the image on success?
Hope that helps
Seem like you want to remove all div with id images, but id is unique, you can use class instead:
<div class='images'><img class='center_loadingImage' align='middle' src='loading.gif' alt='Loading Image'></div>
then you can do:
$('.images').remove()
With your code you can do this:
document.getElementsByClassName("images").remove();
or more like jQuery:
$('.images').remove();
Althoug you can try this too:
var value = document.getElementsByClassName("images");
for (var i = 0; i < value.length; i++) {
$(value).eq(i).remove();
} //-------^^^^^^--------------you can make use of `.eq()` here
What your issue is there is no tag name like 'images' as your var suggests.
var value = document.getElementsByTagName("images");
images is the class name so you can use this:
document.getElementsByClassName("images")
Get element by ID, there's nothing with document.getElementsByTagName("images")
var c = document.getElementById('images');
var i, item = c.childNodes;
for (i = item.length; i--;) {
c.removeChild(item[i]);
}
You should probably be using class="images" instead of id="images" if that element is being rendered multiple times.
But to do this in a loop with raw javascript, you will need to first get the elements, convert them to an array, and then remove them in a loop.
var imageElements = doc.getElementsByClassName('images'),
images = Array.prototype.slice.call(imageElements);
for (var i = 0, l = images.length; i < l; i++) {
images[i].remove();
}
Notice that I don't just loop through imageElements... That's because getElementsBy...() returns a live list, so as soon as you remove() one of them, the list will be mutated and you will start running into undefined elements and javascript errors. To solve this, simply convert the live list to an array with Array.prototype.slice.call() and then loop through that array, removing the elements from the page.

target selected members of an array

I have a series of divs of the same class; some with title attributes set - some without:
<div class="component_wrapper cw1" title="thisTitle1">... </div>
<div class="component_wrapper cw2" title="thisTitle2">... </div>
<div class="component_wrapper cw3" title="thisTitle3">... </div>
<div class="component_wrapper cw4" title="">... </div>
<div class="component_wrapper cw5" title="">... </div>
I've constructed a javascript function that loops through these divs and displays the ones with the title attribute set by setting their css display attribute to "inline":
function checkComponent(e){
var hdrSet = document.getElementsByClassName("component_wrapper");
var titles = {};
for (var i=0; i<hdrSet.length; i++){
if ( !titles[ hdrSet[i].title ] ) {
titles[ hdrSet[i].title ] = true;
hdrSet[i].style.display = "inline";
}
}
}
checkComponent();
the problem is, when I load the page the divs that I'm trying to target display (good), but also 1 of the divs not targeted displays. In the example above, the first four divs display, when all I want is the first three. What's wrong with my code... and is there an better way to construct the function?
Your code checks for duplicate titles, not missing ones. Here's how you could fix that:
function checkComponent(){
var hdrSet = document.getElementsByClassName("component_wrapper");
for (var i = 0; i < hdrSet.length; i++){
if(hdrSet[i].title) {
hdrSet[i].style.display = "inline";
}
}
}
checkComponent();
Also, if you're open to using jQuery, it's much neater and more compatible:
function checkComponent() {
$('.component_wrapper[title]:not([title=""])').css('display', 'inline');
}
checkComponent();

Categories

Resources