What is the javascript in order to only display posts 3 & 4 in order???
Also I need it be dynamic so if I put a 5th post it will only display 4th and 5th posts... I was thinking about something like a date function or a simple incrementor but can't seem to figure it out. I'm new to javascript and have been trying different things but no avail... Thanks in advance...
<!DOCTYPE html>
<html>
<body>
<div id="posts-div">
<h1 class="post-title">post4</h1>
<p class="post">post4</p>
</div>
<div id="posts-div">
<h1 class="post-title">post3</h1>
<p class="post">post3</p>
</div>
<div id="posts-div">
<h1 class="post-title">post2</h1>
<p class="post">post2</p>
</div>
<div id="posts-div">
<h1 class="post-title">post1</h1>
<p class="post">post1</p>
</div>
<script>
// ???
</script>
</body>
</html>
You dont need script for that. You can do it with CSS.. I have changed your html little bit (made posts-div class in html).
.posts-div{
display:none;
}
.posts-div:nth-child(-n+2) {
display:block;
}
<!DOCTYPE html>
<html>
<body>
<div class="posts-div">
<h1 class="post-title">post5</h1>
<p class="post">post5</p>
</div>
<div class="posts-div">
<h1 class="post-title">post4</h1>
<p class="post">post4</p>
</div>
<div class="posts-div">
<h1 class="post-title">post3</h1>
<p class="post">post3</p>
</div>
<div class="posts-div">
<h1 class="post-title">post2</h1>
<p class="post">post2</p>
</div>
<div class="posts-div">
<h1 class="post-title">post1</h1>
<p class="post">post1</p>
</div>
<script>
// ???
</script>
</body>
</html>
You can test it on JSfiddle as well.. https://jsfiddle.net/nimittshah/b5eL3ykx/6/
$('.posts-div:gt(1)').hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<div class="posts-div">
<h1 class="post-title">post4</h1>
<p class="post">post4</p>
</div>
<div class="posts-div">
<h1 class="post-title">post3</h1>
<p class="post">post3</p>
</div>
<div class="posts-div">
<h1 class="post-title">post2</h1>
<p class="post">post2</p>
</div>
<div class="posts-div">
<h1 class="post-title">post1</h1>
<p class="post">post1</p>
</div>
</body>
Try this:
<script>
document.addEventListener("DOMContentLoaded", function () {
var allPosts = document.querySelectorAll(".posts-div");
// This is the number of posts you want displayed
var numberOfPostsToShow = 2;
for (var i = 0; i < allPosts.length; i++) {
if(i > numberOfPostsToShow - 1) {
allPosts[i].style.display = "none";
}
}
});
</script>
This way you will choose how many posts you want to be shown with the numberOfPostsToShow variable.
Let me know if this worked. Regards.
The way I interpreted your question, you need a way to:
show only the first n elements;
add new elements to the top of the list of posts, dynamically;
when you add them, update the visible elements.
Assuming a slightly modified version of your code, which corrects the id/class issue and adds a container for all the posts (this time with a proper id):
<!DOCTYPE html>
<html>
<body>
<div id="posts-container">
<div class="posts-div">
<h1 class="post-title">post4</h1>
<p class="post">post4</p>
</div>
<div class="posts-div">
<h1 class="post-title">post3</h1>
<p class="post">post3</p>
</div>
<div class="posts-div">
<h1 class="post-title">post2</h1>
<p class="post">post2</p>
</div>
<div class="posts-div">
<h1 class="post-title">post1</h1>
<p class="post">post1</p>
</div>
</div>
<script>
// ???
</script>
</body>
</html>
this code will do the trick and manage both the addition and the updates to the visibility of the posts:
function showOnly(visible, query){
var elements = document.querySelectorAll(query);
for (var i = 0; i < elements.length; i++){
if (i < visible - 1){
elements[i].style.display = 'block';
} else {
elements[i].style.display = 'none';
}
}
}
function publishPost(element, visible){
showOnly(visible, '#posts-container .posts-div')
var elements = document.querySelectorAll('#posts-container .posts-div');
element.style.display = 'block';
if (elements.length > 0) {
document.querySelector('#posts-container').insertBefore(element, elements[0]);
} else {
document.querySelector('#posts-container').appendChild(element);
}
}
The showOnly function (to be called with the number of elements to be shown and the string that identifies the elements with querySelectorAll) will only make visible the first n elements identified by the string. You can use it independently of the rest of the code if needed.
The publishPost function, on the other hand, is strictly dependent on the modified html above (to use it elsewhere you will need to adjust the strings fed to querySelector and querySelectorAll). It takes the element to be published as the first argument, the number of elements that need to be visible as the second. Then it updates the list of posts prepending the new one to it, and it also updates which posts are visible.
This is a code sample that uses it:
var elDiv = document.createElement('div');
var elH1 = document.createElement('h1');
var elP = document.createElement('p');
elDiv.classList = 'posts-div';
elH1.classList = 'post-title';
elP.classList = 'post';
elH1.innerText = 'some title';
elP.innerText = 'some text for the post';
elDiv.appendChild(elH1).appendChild(elP);
publishPost(elDiv, 2);
showOnly
This function starts by getting a list of the elements whose visibility must be managed:
var elements = document.querySelectorAll(query);
then it loops through the list and examines each element:
for (var i = 0; i < elements.length; i++){
if it has to be visible, it sets the style.display property to 'block':
if (i < visible){
elements[i].style.display = 'block';
otherwise it sets it to 'hidden':
else {
elements[i].style.display = 'none';
publishPost
This function starts by showing only n-1 elements (because it will need to add a new, visible element to the top of the list):
showOnly(visible - 1, '#posts-container .posts-div')
then it retrieve the current posts:
var elements = document.querySelector('#posts-container .posts-div');
it makes the new element visible:
element.style.display = 'block';
finally, it adds the element to the top of the list (the different syntax depends on wether the list is empty):
if (elements.length > 0) {
document.querySelector('#posts-container').insertBefore(element, elements[0]);
} else {
document.querySelector('#posts-container').appendChild(element);
}
Related
I am trying to iterate through the parent class "cardTags" to change the background color of each child div "tag" depending on what the value is (using .textContent)
For HTML I have:
<div class = 'card'>
<div class='cardTags'>
<div class='tag' id='tag1'>
<header> Auction </header>
</div>
<div class='tag' id='tag2'>
<header> 3d 40m 23s left </header>
</div>
<div class='tag' id='tag3'>
<header> $39 </header>
</div>
</div>
</div>
<div class = 'card'>
<div class='cardTags'>
<div class='tag' id='tag1'>
<header> Sell </header>
</div>
<div class='tag' id='tag2'>
<header> Used </header>
</div>
<div class='tag' id='tag3'>
<header> $59 </header>
</div>
</div>
</div>
For Javascript
function checkTags() {
var category = document.getElementById('tag1');
var condition = document.getElementById('tag2');
var specialty = document.getElementById('tag3');
var textCategory = category.textContent;
var textCondition = condition.textContent;
var textSpecialty = specialty.textContent;
if (textCategory = "Auction") {
category.style.backgroundColor = "#00FF00";
} else if (textCategory = "Trade" {
category.style.backgroundColor = "#00FF00";
} else {
category.style.backgroundColor = "#00FF00";
}
if (textCondition.length = 'Used') {
condition.style.backgroundColor = '#f75555';
} else if (textCondition = 'New') {
condition.style.backgroundColor = '#2fb62f';
} else {
condition.style.backgroundColor = '#f9f906';
}
}
I know the javascript above will only look at 1 div "cardTags" not all the other ones, which is why I am trying to know how can I iterate through each "cardTags" div and see the child divs inside and change the background colors of those divs depending on the values within them. Currently javascript only recognizes one set.
1. id attributes should be unique, currently you have the same id on more than one child element of the parent divs. So you should use the shared className for the children.
2. I modified the classNames of each child tag to be tag1, tag2, tag3, respectively on each set of children.
3. You had some typo's or badly formatted code as well, where you were missing a parenthesis on one of your else-if statements.
4. You were assigning values instead of doing equality comparison in your if and else-if, so I fixed that as well.
5. Also, you were attempting to do comparison of string values and the text content of the headers had leading and trailing space, so I added the trim() function on each call to textContent to remove the extra whitespace for equality comparison.
6. You also had one string comparison where you had appended .length at the end of the string variable, which was causing issues as well.
7. Please see the following for a working example:
window.addEventListener("DOMContentLoaded", () => {
checkTags();
});
function checkTags() {
//get the parents
const parents = document.querySelectorAll('div.cardTags');
parents.forEach((el) => {
const category = el.querySelector('div.tag1');
const condition = el.querySelector('div.tag2');
const specialty = el.querySelector('div.tag3');
const textCategory = category.querySelector('header').textContent.trim();
const textCondition = condition.querySelector('header').textContent.trim();
const textSpecialty = specialty.querySelector('header').textContent.trim();
if (textCategory === "Auction") {
category.style.backgroundColor = "#00FF00";
} else if (textCategory === "Trade") {
category.style.backgroundColor = "#00FF00";
} else {
category.style.backgroundColor = "#00FF00";
}
if (textCondition === 'Used') {
condition.style.backgroundColor = '#f75555';
} else if (textCondition === 'New') {
condition.style.backgroundColor = '#2fb62f';
} else {
condition.style.backgroundColor = '#f9f906';
}
});
}
<div class = 'card'>
<div class='cardTags'>
<div class='tag1'>
<header> Auction </header>
</div>
<div class='tag2'>
<header> 3d 40m 23s left </header>
</div>
<div class='tag3'>
<header> $39 </header>
</div>
</div>
</div>
<div class = 'card'>
<div class='cardTags'>
<div class='tag1'>
<header> Sell </header>
</div>
<div class='tag2'>
<header> Used </header>
</div>
<div class='tag3'>
<header> $59 </header>
</div>
</div>
</div>
html File:
I have used some divs and inside i have introduced some titles and images.
In the search bar i just want that when i enter a title the full div appears on the screen when i search.
<body>
<div class="input">
<input type="text" placeholder="Search.." id="searchbar" onkeyup="search_bar()">
<button type="submit"><i class="fa fa-search"></i></button>
</div>
<div class="s10plus" id="divs">
<h2>Samsung Galaxy S10 Plus</h2>
<img src="Images/s10plus.png"></img>
<p id="precios10">Price : $600</p>
</div>
<div class="samsunga10">
<h2>Samsung Galaxy A10</h2>
<img src="Images/a10.png"></img>
<p id="precioa">Price:$600</p>
</div>
<div class="samsunga20">
<h2>Samsung Galaxy A20</h2>
<img src="Images/a20.png"></img>
<p id="precio">Price:$600</p>
</div>
</body>
file.js
function search_bar() {
var a;
var search = document.getElementById('searchbar');
var filter = search.input.toLowerCase();
var ul = document.getElementsByClassName('s10plus');
var nodes = ul.getElementsByTagName('h2').length;
for (i = 0; i < nodes; i++) {
a = nodes[i].getElementsByTagName('h2')[0];
if (a.innerHTML.toLowerCase().indexOf(filter) > -1) {
nodes[i].style.display = "";
} else {
nodes[i].style.display = "none";
}
}
}
Could you share a Codepen or Codesandbox or add a snipped here in SO?
in your Js code:
"li" is not defined which makes it hard to understand your code exactly.
Also, setting display: "", is not a valid css property. I recommend setting it to display: "inherit".
The class "s10plus" at:
var ul = document.getElementsByClassName('s10plus');
will always get 1 element since in your html only one div has that class.
Try to adjust these issues and see if you can get any further
This code is supposed to be looping and adding multiple divs, but it isn't working. When I click it, only one div appears. If I click again, nothing happens.
<body>
<div class="start" >
<div id = "coba">
</div>
<div id = "cobi">
</div>
</div>
<script>
var divs = document.getElementById("coba").addEventListener("click", function () {
for (var i = 1; i < 100; i++) {
var di = document.createElement('div');
document.getElementById('coba').appendChild(di);
}
});
</script>
</body>
Thanks for your help
Your code does not work because you did not do anything with the variable "i" in the for statement. If you look at the fiddles of user2181397 & meghan Armes you will see how they added a line in the script to put it to work.
I tested the below in my IDE and it works just fine:
<body>
<div class="start" style="margin-top:50px; color:black;">
<div id = "coba">
<p>Click Me</p>
</div>
<div id = "cobi">
</div>
</div>
<script>
var divs = document.getElementById("coba").addEventListener("click", function() {
for (var i = 1; i < 100; i++) {
var di = document.createElement('div');
di.innerHTML=i;
document.getElementById('coba').appendChild(di);
}
});
</script>
</body>
Is it possible to get the ids of the 2 div tags on clicking the button, using javascript?
<div id="main">
<div id="content">
</div>
<button onclick="function();">show it</button>
</div>
I have 2 div tags here. The 1st div is in the main div while the content div is inside the main div and the button is inside the main div as well.
Is it possible to get the main and content id of the 2 div tags on clicking the button?
EXPECTED OUTPUT when I press the button:
alert: main
alert: content
You need to pass the element to the function. Then you can use parentNode to get the DIV that contains the button. From there, you can use querySelector to find the first DIV in the parent.
function showIt(element) {
var parent = element.parentNode;
alert(parent.id);
var content = parent.querySelector("div");
alert(content.id);
}
<div id="main">
<div id="content">
</div>
<button onclick="showIt(this);">show it</button>
</div>
<div id="main2">
<div id="content2">
</div>
<button onclick="showIt(this);">show it</button>
</div>
<div id="main3">
<div id="content3">
</div>
<button onclick="showIt(this);">show it</button>
</div>
document.getElementById('button').onclick = function () {
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
var id = divs[i].getAttribute('id');
alert(id);
}
};
http://jsfiddle.net/jm5okh69/1/
This should work in all browsers and uses the cleaner .id method.
var button = document.getElementById('button');
button.onclick = getIDs;
function getIDs(){
var id,divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
id = divs[i].id // .id is a method
alert(id);
}
}
<div id="main">
<div id="content"></div>
<button id="button">show it</button>
</div>
I want to loop through all of the p tags on my web page and then write them to the end of the web page. I thought that this for loop would work but so far it is giving me an error.
How would I be able to do this and then append the text that is in the tag to the end of the page?
function forLoopTest() {
var i; //indexing tag for looping through all of the array elements
//for loop to loop through the pp array starting at index of zero
for (i = 0; i < pp.length;i++)
{
document.writeln("<br>" + pp[i].innerHTML); //write to the end of the page of each element
}
}
HTML Code:
<!DOCTYPE html>
<html>
<body>
<div id="main">
<p id="AA">A</p>
<p id="BB">B</p>
<p id="CC">C</p>
<p id="DD">D</p>
<p id="EE">E</p>
</div>
<p id="demo"></p>
<script>
var x = document.getElementById("main");
var pp = x.getElementsByTagName("p"); //creates an array of p elements
document.getElementById("demo").innerHTML = 'The first paragraph inside "main" is ' + pp[1].innerHTML;
function forLoopTest() {
var i;
for (i = 0; i < pp.length;i++) {
document.writeln("<br>" + pp[i].innerHTML;
}
}
forLoopTest();
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<div id="main">
<div id="main">
<p id="AA">A</p>
<p id="BB">B</p>
<p id="CC">C</p>
<p id="DD">D</p>
<p id="EE">E</p>
</div>
<p id="demo"></p>
<p style="color:blue;margin-left:20px;">This is a paragraph.</p>
<p id="A">A</p>
<p id="B">B</p>
<p id="C">C</p>
<p id="D">D</p>
<p id="E">E</p>
<div>Test</div>
</div>
<p id="demo"></p>
<script>
var x = document.getElementById("main");
var pp = x.getElementsByTagName("p"); //creates an array of p elements
var divTag = x.getElementsByTagName("div"); //creates an array of div elements
document.getElementById("demo").innerHTML = 'The first paragraph inside "main" is ' + pp[1].innerHTML;
function forLoopTest() {
var i;
for (i = 0; i < pp.length;i++) {
document.writeln("<br>" + pp[i].innerHTML;
}
}
var fragment = document.createDocumentFragment();
Array.prototype.forEach.call(document.getElementsByTagName('p'), function (element) {
Array.prototype.forEach.call(element.childNodes, function (childNode) {
fragment.appendChild(childNode.cloneNode(true));
});
});
document.body.appendChild(fragment);
</script>
</body>
</html>
if you read the error it tells you you have a syntax problem and are misisng a ).
You didn't close write()
document.writeln("<br>" + pp[i].innerHTML;
Should be
document.writeln("<br>" + pp[i].innerHTML);
DEMO
There are numerous way to do it, one solution might be.
HTML
<div id="main">
<p id="AA">A</p>
<p id="BB">B</p>
<p id="CC">C</p>
<p id="DD">D</p>
<p id="EE">E</p>
</div>
<p id="demo"></p>
Javascript
var fragment = document.createDocumentFragment();
Array.prototype.forEach.call(document.getElementsByTagName('p'), function (element) {
Array.prototype.forEach.call(element.childNodes, function (childNode) {
fragment.appendChild(childNode.cloneNode(true));
});
});
document.body.appendChild(fragment);
HTML after
<div id="main">
<p id="AA">A</p>
<p id="BB">B</p>
<p id="CC">C</p>
<p id="DD">D</p>
<p id="EE">E</p>
</div>
<p id="demo"></p>
ABCDE
On jsFiddle
Warning: cloneNode() may lead to duplicate element IDs in a
document.
This is also true if blindly copying the innerHTML of the elements.