Making cards with javascript and html - javascript

I am supposed to make 9 cards. Use a for loop to create t.
When it says it is number 1, that should increment by the number that it is in the loop.
Add the number of the loop to a data attribute.
Create a CSS class for the card that gives it the styling of the image above.
Every odd card should have a background color of #52ce90.
The color of the text should change to white.
I have tried, but i cant figure out how to do it.
Here is my code:
var div = document.createElement("div");
var newCard = "test";
var i;
for (let i = 1; i <= 9; i++) {
newCard += "Box number" + i "<br>";
}
<div class="container" id="Container">
<div class="card" id="card">
<div class="card--header">
<h1 class="card--number--text">
Card number
</h1>
</div>
<div class="card--by">
By
</div>
<div class="card--time">
43 minutes ago
</div>
<button class="card--button"> View on site</button>
And how to style in css, what class or id should i use, and how to get the boxes up?

Here you have code that will append card-odd class to odd values. Know you can style it as you wish
let container = document.querySelector('.container');
for (let i = 1; i <= 9; i++) {
let myDiv = document.createElement("div");
if (i%2 === 0) {
myDiv.innerHTML = "<div class=\"card\">"+ i +"</div>"
}
else {
myDiv.innerHTML = "<div class=\"card card-odd\">"+ i +"</div>"
}
container.appendChild(myDiv);
}
here you have a fiddle:
https://jsfiddle.net/06Lnghvw/
Also you can simply style odd and even card using pure CSS. Please read: https://www.w3schools.com/cssref/sel_nth-child.asp

I have created a snippet that match your requirements. See it here:
var container = document.getElementById("container");
for( var i=1;i <=9; i++)
{
var el = document.createElement("div");
el.className ="card";
el.id = "card" + i;
el.innerHTML = "ok";
container.append(el);
}
.card:nth-child(odd) {
background: #52ce90;
color: #fff;
}
<div id="container">
</div>

Related

looping throug divs and giving them id and then making them clickable

I am trying to make multiple div inside my loop display there own unique message when they are clicked.
But I can't get the code to work. what I am trying to do is...
div1 = hello im div1, div2 = hello im div2.
The divs display on the page as they should but I can't get the click message to work.
Thanks in advance for any help or advice :)
<script type="text/javascript">
var idcontainer = "";
var divs = "";
var clickcontent;
for (i = 1; i < 5; i++) {
divs += `<div class="divs" id="div${i}">Test${i}</div>`;
clickcontent += "Hello i am div" + i;
idcontainer += "#div" + i;
}
console.log(idcontainer);
$("#output").html(divs);
$(idcontainer).click(function(e) {
e.preventDefault();
alert(clickcontent);
});
</script>
You dont need id for that, just store content in data attr and show in click as below
var idcontainer = '';
var divs = '';
var clickcontent
for(i=1;i < 5;i++){
clickcontent = 'Hello i am div' + i;
divs += `<div class="divs" id="div${i}" data-content="`+clickcontent+`">Test${i}</div>`;
idcontainer += '#div' + i;
}
// console.log(divs)
$("#output").html(divs);
$('.divs').click(function (e) {
alert($(this).data('content'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output"></div>
To select many divs you need to separate their ids by comma; now the idcontainer looks like this - #div1#div2..., so the jquery won't yield any element (check out this to find out why). If you were to store their ids in an array like:
var idcontainer = [];
var divs = '';
var clickcontent
for(i=1;i < 5;i++){
clickcontent = 'Hello i am div' + i;
divs += `<div class="divs" id="div${i}" data-content="`+clickcontent+`">Test${i}</div>`;
idcontainer.push('#div' + i);
}
And then use the jquery like this:
$(idcontainer.join(', ')).click(function (e) {
e.preventDefault();
alert(clickcontent)
});
This would work.
You can use the following code to generate divs dynamically and append to any tag you want, here I have appended to a body tag.
// Creating Divs and assign class by the name of "dynamicDiv"
for(i=1;i < 5;i++){
let div = document.createElement('div');
div.textContent = `I am div ${i}`;
div.className = 'dynamicDiv';
$("body").append(div);
}
// Attaching click event for each generated div by using class name
$('.dynamicDiv').on('click', function () {
alert($(this).text()); // Displaying the text of div
});

why `card` element is not duplicated 4 times

Why is card element not duplicated 4 times?
function generate4Cards() {
for (var i=0; i < 4; i++) {
var card = document.getElementById('card');
document.body.appendChild(card);
}
}
<body onload="generate4Cards()">
<div id="card">I am a card</div>
</body>
When you call appendChild with an existing element, that element will be removed from its former position in the DOM and appended to the new container. You'll have to explicitly create the div on each iteration instead.
But, having duplicate IDs in a single document is invalid HTML, so probably best to remove the id (or use a class instead):
for (var i = 0; i < 4; i++) {
var card = document.createElement('div');
card.textContent = 'I am a card';
document.body.appendChild(card);
}
Another option is to use cloneNode:
var originalCard = document.querySelector('div');
for (var i = 0; i < 4; i++) {
var card = originalCard.cloneNode(true);
document.body.appendChild(card);
}
<div>I am a card</div>
foo.append(bar) puts bar at the end of foo.
If I put my car at the end of my road, and then put my car at the end of my drive then I don't have two cars.
append only puts bar where you tell it to put it.
It doesn't duplicate it because it isn't supposed to.
Here is the sample code you are looking for -
<html>
<head>
<script>
function generate4Cards() {
for (var i = 0; i < 4; i++) {
var card = document.createElement('div');
card.textContent = 'I am a card';
document.getElementById('cardHolder').appendChild(card);
}
}
</script>
</head>
<body onload="generate4Cards()>
<div id="cardHolder"></div>
</body>
</html>

Replace innerHTML of divs with same class based on content

I am trying to only replace the content of the div with the "replace this".
The content of each div is dynamically created, so i have to check which class needs to be changed. I tried it with a for-loop and so far I am getting the right div but having trouble changing its content. The main problem is that they all have the same class. How can I put the new text into the correct div without changing the others?
var x = document.getElementsByClassName("class_name");
var teststring = "rep";
for (i = 0; i < x.length; i++) {
if (x[i].toString().indexOf(teststring) > 0) {
this.innerHTML = "text3";
}
}
<div class="class_name">
text1
</div>
<div class="class_name">
text2
</div>
<div class="class_name">
replace this
</div>
Declare the variable with let in the for loop which will create it's own scope within curly braces ({...}). Instead of using this, use the current element with x[i]. x[i] refers to the element itself, you have to take the content from it.
I will prefer textcontent instead of innerHTML
var x = document.getElementsByClassName("class_name");
var teststring = "rep";
for (let i = 0; i < x.length; i++) {
if (x[i].textContent.indexOf(teststring) > 0) {
x[i].textContent = "text3";
}
}
<div class="class_name">
text1
</div>
<div class="class_name">
text2
</div>
<div class="class_name">
replace this
</div>
Use x[i].innerHTML not this.innerHTML
var x = document.getElementsByClassName("class_name");
var teststring = "rep";
for (i = 0; i < x.length; i++) {
if(x[i].innerHTML.indexOf(teststring) !== -1) {
x[i].innerHTML = "text3";
}
}
DEMO
https://jsfiddle.net/0cmz4pvk/5/

Select all element with same tag name using javascript and highlight content partially

I made a code that should highlight searched string but it is not working.
Here is the code:
<body>
<div>div is here</div>
<div id="divid">
<div>this is a div 1</div>
<div> this is a div 2</div>
<div> this is a div3</div>
</div>
<div> another div is here</div>
</body>
Here is a javascript code.
function checkit(){
var hlWord = "div";
var nregex = new RegExp(hlWord,"gi");
var div = document.getElementById("divid").getElementsByTagName('div');
for(var i=0; i <= div.length; i++){
var div1 = div[i].innerHTML;
var rword = div1.replace(nregex,"<b>"+hlWord+"</b>");
div1.innerHTML = rword;
}
}
There are begginer mistakes in your code. Let me correct them:
function checkit(){
var hlWord = "div"; //Define string that will be emphasized by <b> tag
var nregex = new RegExp(hlWord,"gi");//Create global, case-insensitive regexp
var div = document.getElementById("divid").getElementsByTagName('div'); //Get element collection of divs in div#divid
for(var i=0; i < div.length; i++){ //Loop through my element collection
var div1 = div[i].innerHTML; //Get the innerHTML of on of the divs
var rword = div1.replace(nregex,"<b>"+hlWord+"</b>"); //Surround my string with <b>
div[i].innerHTML = rword; //Change the innerHTML back
}
}
You used this for condition: i<=div.length. This is wrong. Do not forget, that we count from 0 so: [0, 1, 2, 3].length = 4. Last element for such array has index 3. The [] is an array literal.
By mistake, you assigned div1.innerHTML. div1 was a string. The element you want to change is div[i].
I made a JSFiddle too!
The problem with you code will be, amongst other problems, that nested div elements will be broken. You should use some kind of recursion if you want to highlight the word 'div'.
Here is such a function:
function highLight(term,root){
var allDiv = root.querySelectorAll('div'),
replacer = function(a){return '<span class="highlight">'+a+'</span>'};
for (var i=0; i<allDiv.length; i+=1){
if (allDiv[i].querySelectorAll('div').length){
highLight(term, allDiv[i]);
} else {
var re = RegExp('('+term+')','gi');
allDiv[i].innerHTML = allDiv[i].innerHTML.replace(re,replacer);
}
}
}
And here is a jsfiddle to play around with it
A more advanced jsfiddle
You have several errors: there you go:
http://jsfiddle.net/55U6j/1/
function checkit(){
var hlWord = "div";
var nregex = new RegExp(hlWord,"gi");
var divs = document.getElementById("divid").getElementsByTagName('div');
for(var i=0; i < divs.length; i++){
var div = divs[i];
var html = div.innerHTML;
var rword = html.replace(nregex,"<b>"+hlWord+"</b>");
div.innerHTML = rword;
}
}

How to fill a div with content under the condition that the div has no childs?

For example, when I have:
<div class="abc123"></div> <!-- no child div -->
I want to insert a new div in it:
<div class="xyz">some content</div>
So that the outcome is:
<div class="abc123">
<div class="abc">Some Content</div>
</div>
How can I implement this using javascript?
in jQuery:
$(".abc123").each(function() {
if (this.children(".abc").length == 0) {
$(this).append('<div class="xyz">some content</div>');
}
});​
in Simple JS
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
if (divs[i].childNodes.length == 0) { // testing if it has not child
var newdiv = document.createElement('div');
newdiv.innerHTML = "some content";
newdiv.className = "xyz";
divs[i].appendChild(newdiv);
}
}​
Edit:
This following piece of code produces the same effect as done in the above mentioned jQuery code(edited in light of the comment by RobW ):
var divs = document.getElementsByClassName("abc123");
for (var i = 0; i < divs.length; i++) {
if (divs[i].getElementsByClassName("abc").length == 0) {
var newdiv = document.createElement('div');
newdiv.innerHTML = "some content";
newdiv.className = "xyz";
divs[i].appendChild(newdiv);
}
}​
Maybe you would like to take a look at this question: How to check if element has any children in Javascript?
Seems like what you are looking for :)
With jQuery:
if ($('.abc123 div').length == 0) {
$('.abc123').append('<div class="xyz">some content</div>');
}​

Categories