Creating dynamic divs - javascript

Trying to make a dynamic div but i don't know how. Wrote a solidity smart contract that accepts an array of struct. In the smart contract i can use a get function to display the data inside. Data in the array is treated like a history, it consists of amount (making a crowdfund site), date, currency used, etc. Since the get function in the smart contract can only extract one part of the array, i thought of putting the get function into the while loop and extract the whole history array..
<div id=set>
<a>value1</a>
<a>value2</a>
</div>
I'm trying to dynamically create another div with the same amount of < a > in the div. If i had 10 sets of data to display in that div, i wish to create only 10 sets of that div. Can createElement() be used to do that? Couldn't find any solution that works. Totally have no idea on how to create it. Can someone please help.
Would it be rational to extract the data from the array using a while loop and putting it in a div to display or would it use too much gas for this to work?

I don't get why would you want to do this, but you can do like this:
$('#set a').each(function(){
$('#set').after( "<div></div>");
});
It selects all of the <a>...</a> inside the <div id="set">...</div> element, and for each one of those inserts a <div></div> element. It inserts the element right next to #set but you can change that to any other element you could select.
I'm supplying jQuery code since you tagged the question as jQuery.
Hope it helps,

You can get the number of anchor tags by using this function getElementsByTagName('a').length from the hosting div. Then use that number to create new divs. This solution is done using vanilla JS.
function createDynamicDivs(){
var newDiv = document.createElement("div");
var noOfAnchors = document.getElementById('set').getElementsByTagName('a').length;
for(var i=0;i<noOfAnchors;i++){
var newContent = document.createElement("a");
newContent.textContent= "Test ";
newDiv.appendChild(newContent);
}
document.getElementById('new').appendChild(newDiv);
}
<div id=set>
<a>value1</a>
<a>value2</a>
</div>
<div id="new"></div>
<button onclick="createDynamicDivs()">Generate</button>

Related

Python - Beautifulsoup - looping divs tags with same class names

I'm wondering how to scrap information off a website where there is multiple elements that have the same identifiers from which I want to scrap price data from. The issue I'm having is that when I loop through each div and print() I see its pasted multiple times in the console. I assume this is du to the div I'm locating encapsulated multiple elements with the same tag + classname.
HTML Page notation
GraphicPrice = soup.findAll('div', class_='col')
for price in GraphicPrice:
prices = price.find('span', class_='price__amount')
if prices is None:
pass
else:
print(prices.text)
Output:
£859.99
£859.99
£1,049.99
£1,049.99
£829.99
£829.99
£899.99
£899.99
£999.95
£999.95
£999.95
£999.95
What I want is to eliminate the duplicate information and understand how to refactor my code to prevent this from happening.
I want every elements on the page prices to be printed. Currently I get the prices but it's duplicated 3 times.
Any help would be appreciated. (I'm still leaning) :)
first, you scrap all div tags with "col" class
soup.findAll('div', class_='col')
this div tag has one span class and that one class has two other nested span tags.
so, if you code like this
price.find('span', class_='price__amount')
it scraps two span tags with "price_amount" on each div tag.
that represents a wrong class.
if you want a second span tag then your code is like this.
soup.findAll('span', class_='price--sale--colored').find('span', class_='price__amount')
Use .select('span') to get object from inner of the selected object like
GraphicPrice = soup.findAll('div', class_='col')
for price in GraphicPrice:
prices = price.select('span')

How do I iterate an output data from an array in an object

I am trying to create a daily weather app and i'm having issues trying to figure out how to output the data into cards for all seven days. its currently only outputting the last day. I know that its because if am setting it to $("#card__days").html( but im not sure how to add onto the current html.
Is there also any easier way to output this information? I feel like I did way too much for a simple task. Thank you
function updateDaily(data) {
Object.keys(data.daily.data).forEach(function (i) {
// call to find what the day is.
let date = calculateDay(data.daily.data[i].time);
console.log(data.daily.data[i]);
let iteration = i;
let high = data.daily.data[i].temperatureHigh;
let low = data.daily.data[i].temperatureLow;
let feels = data.daily.data[i].apparentTemperature;
let desc = data.daily.data[i].summary;
let icon = data.daily.data[i].icon;
let skycons = new Skycons({ color: "#3e606f" });
$("#card__days").html(`
<div class="card__daily">
<h2 id="daily__date"${iteration}">${date}</h2>
<canvas src="" alt="icon" class="icon" id="daily__icon${iteration}"></canvas>
<div class="degrees">
<h3 id="daily__high${iteration}" class="temp">${high}℉ / ${low}℉</h3>
</div>
<h3 id="daily__desc${iteration}">${desc}</h3>
</div>
`);
skycons.add(
document.getElementById("daily__icon" + i),
icon
);
skycons.play();
});
}
EDIT: Here is what it currently looks like and some data from the API.
Current Visual Output
Some data from Object
If you want to make all seven cards appear, use .append() instead:
$("#card_days").append(/* Your card HTML */);
You only see the last card because in each iteration the for loop overwrites the html with the latest ${iteration} data, instead of creating a new piece of data and a new html element. To fix this:
You could use the $("#card_days").append method, from the other comment in this thread, but personally in a similar situation I used:
$("#card_days").insertAdjacentHTML('beforeend', html) method, it will insert the code you give it as an html parameter just before the closing tag of the element you selected.
As a side note, I only used insertAdjacentHTML because I needed the user to be able to create and delete these html elements, so their amount could not be predefined. In your case, it seems like you know you need exactly 7 elements. If this is the case, I would suggest to stick with html and css, and the only usage of JS would be to update a placeholder text with the newly-fetched data. Hard-coding in this case seems a bit more error-proof :)

Create a region on HTML with changing values

I am a beginner in HTML and I want to create a region on a HTML page where the values keep on changing. (For example, if the region showed "56" (integer) before, after pressing of some specific button on the page by the user, the value may change, say "60" (integer) ).
Please note that this integer is to be supplied by external JavaScript.
Efforts I have put:
I have discovered one way of doing this by using the <canvas> tag, defining a region, and then writing on the region. I learnt how to write text on canvas from http://diveintohtml5.info/canvas.html#text
To write again, clear the canvas, by using canvas.width=canvas.width and then write the text again.
My question is, Is there any other (easier) method of doing this apart from the one being mentioned here?
Thank You.
You can normally do it with a div. Here I use the button click function. You can do it with your action. I have use jquery for doing this.
$('.click').click(function() {
var tempText = your_random_value;
// replace the contents of the div with the above text
$('#content-container').html(tempText);
});
You can edit the DOM (Document Object Model) directly with JavaScript (without jQuery).
JavaScript:
var number = 1;
function IncrementNumber() {
document.getElementById('num').innerText = number;
number++;
}
HTML:
<span id="num">0</span>
<input type='button' onclick='IncrementNumber()' value='+'/>
Here is a jsfiddle with an example http://jsfiddle.net/G638z/

Wrapping a jquery validate span.error with nested divs

Heyo. This is my first stack overflow post because I am stumped and not finding many people who are trying to accomplish the same thing. I've tried using jquery .before(), .after(), and .wrap() to resolve this. I was initially using css :before and :after pseudo-elements, but as that won't work for legacy browsers, I've decided to use jquery.
I already have several forms on several pages with validation working. The error messages vary in length. We were using a static, one size background image on the default span element, so content was bleeding out on longer error messages. I built a flexible rounded corner series of nested divs to allow the error box to grow or shrink dynamically. The html I want to output is:
<div class="errorWrap">
<div class="errorTop"><span></span></div>
<div class="errorContent">
<span class="error">This is an error</span>
</div>
<div class="errorBottom"><span></span></div>
</div>
Here's an example of a solution I tried, but I'm still pretty new to javascript.
$('.error').before('<div class="errorWrap"><div class="errorTop"><span></span></div><div class="errorContent">');
$('.error').after('</div><div class="errorBottom"><span></span></div></div>');
Correct me if I'm wrong, but I think that I have the right idea with the jquery. But it's just kind of sitting there, not in any function being called. So I imagine that since the code isn't re-executing, it just doesn't show up. Is there an appropriate function to wrap this in? I'm certain I'm just not attacking this from the right direction. Any help is super appreciated.
the plugins "before" and "after" dont take html as string. you cannot start a div in one and close it in an other.
Either you take your current html and generate a new html string which you append where you want to or you use the "wrap" plugin http://api.jquery.com/wrap/
Using pure HTML
$(".error").html("<div class='beforeContent'>" + $(".error").html() + "</div>");
Using wrap (http://api.jquery.com/wrap/)
$(".error").wrap("<div class='beforeAndAfter'></div>");
If you want to show an error div after focus out of an input then you have to create it using html/wrap as Luke said and then you have to append it in ot the dom useing
$('.errorWrap').insertAfter('.focusedElement');
But there are other methods available to insert a new element like append/appendTo e.t.c,
I ended up fixing this problem on my own using jquery to create the div and it's nesting on pageload, the divs are generated with an error class that gives display:none. A custom errorPlacement function nests the error in the correct div. Then I used a custom validator highlight function to remove the class that hides the element. Then I used the unhighlight function to re-add the class to re-hide the div.
$(function() {
//Generate the elements and assign attributes
var errorWrap = document.createElement('div');
$(errorWrap).addClass('errorWrap hideError');
var errorTop = document.createElement('div');
$(errorTop).addClass('errorTop');
var topSpan = document.createElement('span');
var errorContent = document.createElement('div');
$(errorContent).addClass('errorContent');
var errorBottom = document.createElement('div');
$(errorBottom).addClass('errorBottom');
var bottomSpan = document.createElement('span');
//Place the elements directly after each dd element
$("dl > dd").append(errorWrap);
$("div.errorWrap").append(errorTop)
.append(errorContent)
.append(errorBottom);
$("div.errorTop").append(topSpan);
$("div.errorBottom").append(bottomSpan);
//Add custom validator defaults
$.validator.setDefaults({
errorPlacement: function(error, element) {
$(element).nextAll('.errorWrap').children('.errorContent').append(error);
},
highlight: function(element) {
$(element).nextAll('.errorWrap').removeClass('hideError');
},
unhighlight: function(element) {
$(element).nextAll('.errorWrap').addClass('hideError');
}
});
}
Although I'm sure this could have been done more shorthand, I really like this technique because I didn't have to update any of my pages that contained forms to get it to work. All of the nested divs are dynamically created by javascript, so I can include a global file to any page with forms and it will just work. Thanks for all who offered suggestions.

Writing to a non-unique div with Javascript

I'm building a multi-feed RSS reader for school.
aList is the div that encompasses each individual feed (the amount of feeds will fluctuate).
theTitle is the div that will be filled with the attribute of the current feed. Additionally, if clicked, it will load a list of attributes from the current feed into theContent.
I'm wondering how I can dynamically load the attributes into theContent when theTitle is clicked, since theContent and theTitle are going to be non-unique divs (I can't give them IDs).
Thanks for your help in advance,
-Andrew
document.getElementsByClassName('aList').getElementsByTagName('div')
You should look into jQuery selectors for that and other DOM Manipulation. Something like
$("div.theContent").attr("name", "value");
by using jquery, you may use code like the following:
$(".theTitle").bind("click", function(){
$el = $(this);
$el.parent().$(".theContent").load('ajax/content.php?news=' . $el.text());
});
this will make all your links clickable, an on click, update their corresponding content divs with the value of ajax/content.php?news=theTitle-value
Use a nice Javascript library such as Prototype or jQuery. Seems petty now, but these frameworks save you tons of time in the long run.
In both frameworks, you can select that div with:
$('div.theTitle')
With jQuery, you can do:
$('div.theTitle').click( function() {
var title = $(this).text();
var contentDiv = $(this).siblings('div.theContent');
// Do something with contentDiv and the title
} );
This will make every theTitle div have an onClick event that does something with its associated theContent div.
<div class="aList">
<div class="theTitle" onclick="fillContentBox(this)"></div>
<div class="theContent"></div>
</div>
And in your script ...
function fillContentBox(div) {
var theContentDiv = div.parentNode.getElementsByTagName("div")[1];
// statements that do things with theContentDiv
}
You have to be able to determine which element you want to update if you don't want to update more than one. If the elements are grouped inside something else that does have an "id" value, you can take advantage of that.

Categories

Resources