I have multiple div element's which is generated dynamically. I want to access the first class name using javascript. So far i did this:
function changeFilter(cat) {
console.log(cat);
var x = {};
x = document.getElementsByClassName("itemProductList");
console.log(x);
if (cat == x) {
console.log("yes");
} else {
console.log("nope");
}
}
In console I get this:
div.Desserts.itemProductList.item-list.col-md-3.col-lg-3.col-xs-12.col-sm-4,
My div elements that are generated dynamically looks something like this:
<div class="{{product.category}} itemProductList item-list col-md-3 col-lg-3 col-xs-12 col-sm-4" style="float:left; min-height:370px; margin-bottom:20px;" ng-repeat="product in store.products | filter:search | filter:category">
How can I get Deserts from above?
Can someone help me out?
Use the classList property and take the first element.
The function document.getElementsByClassName() will return an iterable with possibly many items, so you can use Array.forEach() to iterate over them, but you have to convert the result to an array first:
const divs = document.getElementsByClassName("itemProductList");
[...divs].forEach(div => console.log(div.classList[0]));
<div class="Desert itemProductList item-list col-md-3 col-lg-3 col-xs-12 col-sm-4">
<div class="Desert itemProductList item-list col-md-3 col-lg-3 col-xs-12 col-sm-4">
<div class="Desert itemProductList item-list col-md-3 col-lg-3 col-xs-12 col-sm-4">
You can split the element's classname on a space and get the first part of that array.
document.getElementsByClassName returns a HTMLCollection which you can iterate over with a for loop.
for(var i=0; i<x.length; i++){
console.log(x[i].className.split(" ")[0]);
}
Related
I've tried to write a script that fire a click on a specific element of an online website (not my website) and at a specific time. The specific time is given by a countdown that run inside the website.
by reading the html file of that website, the code (captured at a generic time) is like that:
<div class="thecountdowndown" id="counting"><div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><div>00</div><small>days</small></div><div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><div>23</div><small>hours</small></div><div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><div>12</div><small>minutes</small></div><div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><div>41</div><small>seconds</small></div></div>
image of the code of the counter.
So it's basically shown a timer, and every second the html code change.
My problem is that i can't figure it out how to write a functions that check when the code up here appear in the html!
This one is not working:
function searchTree(element, matchingTitle){
if(element.title == matchingTitle){
return element;
}else if (element.children != null){
var i;
var result = null;
for(i=0; result == null && i < element.children.length; i++){
result = searchTree(element.children[i], matchingTitle);
}
return result;
}
return null;
}
I may should use var and a "While" loop: while the var has value 0, the function continues to search. but i don't know how to write the "searching" function.
And to say it all, i can't think about a way to start the "click" function after that the "searching" function has detected that the code is appeared.
Can anyone help me?
Update: in other words, there is a countdown on that website that start at midnight. Now, how i can (by using the chrome console) click a button when the countdown show the time "05:45:00"? The button that i want to press is in the same page of the countdown.
// just for simulating change in counter on HTML - already on website / dont inject through dev-tools
var seconds = 45;
setInterval(() => {
document.getElementById("fakeChange").innerHTML = seconds--;
}, 1000);
// is injected through dev-tools / console by yourself
var elIdToObserve = 'counting';
var elIdToSimulateClick = 'submit';
// get the following value by manually calling:
// console.log(document.getElementById(elIdToObserve).innerHTML)
var waitForContentAppearing = `
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><div>00</div><small>days</small></div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><div>23</div><small>hours</small></div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><div>12</div><small>minutes</small></div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><div id="fakeChange">41</div><small>seconds</small></div>
`; // change this to your target content i.e. seconds 46 to 41
setInterval(() => {
if(document.getElementById(elIdToObserve).innerHTML === waitForContentAppearing) {
// Add you own instructions here that should be executed
// Since you mentioned there is a button within the webpage I added a button with id that gets a automated click - the button I added does do something i.e. for visualization I made the button show some text indicating it has been "clicked".
document.getElementById(elIdToSimulateClick).click();
}
}, 500);
<!-- comes from existing website -->
<div class="thecountdowndown" id="counting">
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><div>00</div><small>days</small></div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><div>23</div><small>hours</small></div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><div>12</div><small>minutes</small></div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><div id="fakeChange">46</div><small>seconds</small></div>
</div>
<button id="submit" onclick="document.getElementById('simulationClick').innerHTML = 'Simulated click at timestamp '+Date.now()">Send</button>
<div id="simulationClick">
</div>
You might as well need to select via classes to get the Button you want to click on.
You may have to tweak this a little bit, but it may help.
const clickNow = function(targetElement, elementToClick) {
//May have to play with the selector to get node that holds the value
const timer = document.querySelector(targetElement);
setInterval(()=>{
if(timer.value === "5:40:01 pm") {
clickButton(elementToClick);
}else {
console.log("no yet", timer.value,"5:40:01 pm");
}
},100)
function clickButton(elementToClick) {
const toClick = document.querySelector(elementToClick);
toClick.click();
}
}
clickNow("input[name='display2']",".t");
I have multiple sibling elements, some that are added dynamically and others manually or using JS. Each one has a data attribute of "data-sec_number" with a number value that increases by one for each new element down the page. At the moment I am manually writing these in.
E.g.
<div class="container">
<div class="row resource_sec" data-sec_number=1>
<div class="content sec_number" data-sec_number=1></div>
</div>
<div class="row resource_sec" data-sec_number=2>
<div class="content sec_number" data-sec_number=2></div>
</div>
<div class="row resource_sec" data-sec_number=3>
<div class="content sec_number" data-sec_number=3></div>
</div>
</div>
How can I get the value of attribute "data-sec_number" to match the index of the element .resource_sec within the .container element? E.g. the 3rd .resource_sec element will always have a "data-sec_number" value of 3.
I also have the child element of .resource_sec called .sec_number, which has the same data attribute that should mirror the parent.
The JS I have been trying to use is:
var items = $('.container .resource_sec');
var lastItem = $('.container .resource_sec:last');
var index = items.index(lastItem);
$('.resource_sec').attr('data-sec_number', index);
$('.sec_number').attr('data-sec_number', index);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row resource_sec" data-sec_number=1>
<div class="content sec_number" data-sec_number=1></div>
</div>
<div class="row resource_sec" data-sec_number=2>
<div class="content sec_number" data-sec_number=2></div>
</div>
<div class="row resource_sec" data-sec_number=3>
<div class="content sec_number" data-sec_number=3></div>
</div>
</div>
The meaning of this line
$('.resource_sec').attr('data-sec_number', index);
is to set the attribute value. to select (query) a specific index please use:
$('.resource_sec[data-sec_number=' + index + ']')
or
$(`.resource_sec[data-sec_number=${index}]`)
If you support ES6
UPDATE:
To add a new element in jQuery you may use:
var container = $('.container')
var newElement = $('<div class="row resource_sec"></div>').appendTo(container)
Then, you can fetch the new element index by passing it to the index method,according to Jquery documentation:
If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.
var index = container.index(newElement)
To append index to the new element attribute:
newElement.attr('data-sec_number', index)
I want to hover over on the buttons and want to show a hidden div/panel underneath it by using java script. My Javascript is externally included and works fine, i am trying to use the DOM model to change the style and innerHTML of the div but isnt working. This is my HTML, Javascript and CSS code below. I am even passing parameters to verify which button was hovered but failing.
HTML
<div class="container">
<div class="row anchorbutton">
<div class="col-sm-4 col-xs-12 col-md-4 col-lg-4">
<a href=#><div class=" mainbuttons b1 text-center"
onmouseover="updatepanel(1);" onmouseout="hidepanel()">Workout
Programs</div></a>
</div>
<div class="col-sm-4 col-md-4 col-lg-4 col-xs-12">
<a href=#><div class=" mainbuttons b2 text-center"
onmouseover="updatepanel(2);" onmouseout="hidepanel()"> Diet
Plans</div></a>
</div>
<div class="col-sm-4 col-md-4 col-lg-4 col-xs-12 ">
<a href=#><div class=" mainbuttons b3 text-center"
onmouseover="updatepanel(3);" onmouseout="hidepanel()"> Food
Supplements</div></a>
</div>
</div>
</div>
<div class="container">
<div class="panel panel-default hidden">
<div class="hoverable panel-body hidden"> </div>
</div>
</div>
JS
function hidepanel(){
var panel=document.getElementsByClassName("hidden");
panel.style.display=none;
}
function updatepanel(x){
var desc1="Get fully customized workout programs from our dedicated fitness
experts.";
var desc2="Nutrional advice and diet plans just for your needs!";
var desc3="Our very own state-of-the-art line of supplementations.Click to
Order";
if(x==1){}
document.getElementsByClassName('hidden').style.display='block';
document.getElementsByClassName('hidden').innerHTML='desc1';
}
if(x==2){
document.getElementsByClassName('hidden').style.display='block';
document.getElementsByClassName('hidden').innerHTML='desc2';
}
if(x==3){
document.getElementsByClassName('hidden').style.display='block';
document.getElementsByClassName('hidden').innerHTML='desc3';
}
}
CSS
.hidden{
display: none;
}
I have also tried to change the functionality by changing the function to work on onClick instead of onmousehover but it wont work.Please help me out i have been banging my head.
document.getElementsByClassName() returns an HTML Collection, which is a collection of elements, so saying things like collection.style.display or collection.innerHTML doesn't make a whole lot of sense. I think what you are wanting to do is grab the individual element and update the properties, like so:
document.getElementsByClassName("hidden")[0].
If you need to iterate over the collection, you can access a length property and do a traditional for loop, or you can do an Array.from() using ES6.
function hidepanel() {
var panel = document.querySelector(".hidden");
panel.style.display = "none";
}
function updatepanel(x) {
var desc1 = "Get fully customized workout programs from our dedicated fitness experts.";
var desc2 = "Nutrional advice and diet plans just for your needs!";
var desc3 = "Our very own state-of-the-art line of supplementations.Click to Order";
// make variable so we don't have to search the DOM 2 times for every panel
var hiddenElem = document.querySelector(".hidden");
var panelBody = document.querySelector(".panel-body");
if (x == 1) {
hiddenElem.style.display = 'block';
panelBody.innerHTML = 'desc1';
}
// don't evaluate unnecessarily
else if (x == 2) {
hiddenElem.style.display = 'block';
panelBody.innerHTML = 'desc2';
}
// don't evaluate unnecessarily
else if (x == 3) {
hiddenElem.style.display = 'block';
panelBody.innerHTML = 'desc3';
}
}
.hidden{
display: none;
}
<div class="container">
<div class="row anchorbutton">
<div class="col-sm-4 col-xs-12 col-md-4 col-lg-4">
<a href=#>
<div class=" mainbuttons b1 text-center" onmouseover="updatepanel(1);" onmouseout="hidepanel()">Workout Programs
</div>
</a>
</div>
<div class="col-sm-4 col-md-4 col-lg-4 col-xs-12">
<a href=#>
<div class=" mainbuttons b2 text-center" onmouseover="updatepanel(2);" onmouseout="hidepanel()"> Diet Plans
</div>
</a>
</div>
<div class="col-sm-4 col-md-4 col-lg-4 col-xs-12 ">
<a href=#>
<div class=" mainbuttons b3 text-center" onmouseover="updatepanel(3);" onmouseout="hidepanel()"> Food Supplements
</div>
</a>
</div>
</div>
</div>
<div class="container">
<div class="panel panel-default hidden">
<div class="hoverable panel-body"> </div>
</div>
</div>
Alternatively, you can use the built in document.querySelectorAll(), which returns a NodeList, which does have a built in iterator function (forEach), which makes iterating over the list cleaner/easier.
That would look like so:
document.querySelectorAll(".hidden").forEach(function (elem) {
elem.syle.display = "block";
// etc...
});
First document.getElementsByClassName returns an HTML Collection so you must specify the index of the element you want to use, like: document.getElementsByClassName('hidden')[0].
Second panel.style.display must be a defined as a string, so change none to "none" in your hide function
Working codepen: https://codepen.io/sunrisem/pen/QagPLG
Don't use inline javascript in your html, instead loop the elements and attach an event listener to them. You can set data-attributes on the button, so you could either create an array like shown below holding the texts, or you could put the text as a data-attribute. You'll also need a listener that reacts on the mouse leaving the button, to hide the div again. You should be easily able to change the code to fit your classes...
let div = document.getElementById('d');
let descriptions = [
"Get fully customized workout programs from our dedicated fitness experts.",
"Nutrional advice and diet plans just for your needs!",
"Our very own state-of-the-art line of supplementations.Click to Order"
];
document.querySelectorAll('.btn').forEach(e => {
e.addEventListener('mouseover', ({
target
}) => {
div.innerHTML = descriptions[target.getAttribute('data-nr')];
div.classList.remove('hidden');
}, false);
e.addEventListener('mouseout', () => {
d.classList.add('hidden');
}, false)
});
.hidden {
display: none;
}
div {
margin-top: 10px;
color: red;
}
<button class="btn" data-nr="0">
1
</button>
<button class="btn" data-nr="1">
2
</button>
<button class="btn" data-nr="2">
3
</button>
<div id="d" class="hidden">
</div>
I am trying to append two child 'div' elements with different classes to one parent 'div' element.Here is my code
//javascript
document.getElementById('add').addEventListener('click',function(){
var task = document.getElementById('task').value;
if(task) addTodoTask(task);
});
function addTodoTask(text){
var list = document.getElementById('todo');
var item = document.createElement('li');
var row = document.createElement('div'); //parent inthis case
row.classList.add('row');
var task = document.createElement('div'); //child 1
task.classList.add('col-md-8');
task.classList.add('col-sm-8');
task.classList.add('col-xs-8');
task.classList.add('task');
task.innerText = text;
var buttons = document.createElement('div'); //child2
task.classList.add('col-md-4');
task.classList.add('col-sm-4');
task.classList.add('col-xs-4');
row.appendChild(task);
row.appendChild(buttons);
item.appendChild(row);
list.appendChild(item);
console.log(list);
}
I want to append task(div),buttons(div) to row(also div), that is child1, child2 should be appended to the parent,all of three are 'div's.
When I do this, It is giving
<div class="row">
<div class="col-md-8 col-sm-8 col-xs-8 task col-md-4 col-sm-4 col-xs-
4">hi there
</div><div></div></div>
But I want
<div class="row ">
<div class="col-md-8 col-sm-8 col-xs-8 task">
hi there
</div>
<div class="col-md-4 col-sm-4 col-xs-4">
some other elements
</div>
</div>
How can I fix it? Can anyone help me...
Change this
var buttons = document.createElement('div'); //child2
task.classList.add('col-md-4');
task.classList.add('col-sm-4');
task.classList.add('col-xs-4');
to
var buttons = document.createElement('div'); //child2
buttons.classList.add('col-md-4');
buttons.classList.add('col-sm-4');
buttons.classList.add('col-xs-4');
Be careful on editing variable names while copy pasting
I am attempting to make a player health counter, however I am still getting NaN returned.. Help
Here is my HTML
<!--player 1 hp-->
<div class="row">
<div class="col-sm-6 col-md-6 col-xs-12 col-lg-6">
<h2 class="text-center" id="play1HP">0</h2>
<button onclick="healthCountUp1()">+1</button>
</div>
And my JavaScript
function healthCountUp1(){
var player1HP = parseInt(document.getElementById("play1HP").value);
var add = player1HP + 1;
document.getElementById("play1HP").innerHTML = player1HP;
}
You need innerHTML and not value. This is happening because the h2 element has not an attribute called value. So when you read the value of the h2 you get undefined and when you pass undefined to the parseInt you get NaN.
var player1HP = parseInt(document.getElementById("play1HP").innerHTML);
h2 element doesn't have value property, so parseInt will return NaN. You need to use innerHTML or textContent to get value. Also you need to update with variable add.
function healthCountUp1() {
var player1HP = parseInt(document.getElementById("play1HP").innerHTML);
var add = player1HP + 1;
document.getElementById("play1HP").innerHTML = add;
}
<div class="col-sm-6 col-md-6 col-xs-12 col-lg-6">
<h2 class="text-center" id="play1HP">0</h2>
<button onclick="healthCountUp1()">+1</button>
</div>
function healthCountUp1() {
var player1HP = parseInt(document.getElementById("play1HP").textContent);
var add = player1HP + 1;
document.getElementById("play1HP").textContent = add;
}
<div class="col-sm-6 col-md-6 col-xs-12 col-lg-6">
<h2 class="text-center" id="play1HP">0</h2>
<button onclick="healthCountUp1()">+1</button>
</div>
you had better make variable to store health value in:
<div class="row">
<div class="col-sm-6 col-md-6 col-xs-12 col-lg-6">
<h2 class="text-center" id="play1HP">0</h2>
<button onclick="healthCountUp1()">+1</button>
</div>
javascript:
var health = 0;
function healthCountUp1(){
health++;
document.getElementById("play1HP").innerHTML = health;
}