I can't reset an element in my code.
I have a code that allows me to create spans with each click. However, each click creates additional spans without overwriting the previous ones. I would like this one not to keep the previous spans in value.
This my code :
const fieldText = document.getElementById('fieldDashboardText');
if(info.title != undefined){
isFields = true;
isFirst = true;
const title = info.title;
fieldText.innerHTML = fieldText.innerHTML + '<a class="fiedsInVerbatimDashboard"> Title : </a>' + '<br>';
let newTitle = title.replace(/[,.:;!?()"]+/g, '');
newTitle = newTitle.replace(/[']+/g, ' ');
const features = newTitle.split(' ');
const positiveValues = app.generateLimeOpacity(positive, 'positive');
const negativeValues = app.generateLimeOpacity(negative, 'negative');
const newDataLime = [...positiveValues, ...negativeValues];
var spanCounter = 0;
console.log("Features in tile : ", features);
for (let i = 0; i < features.length; i++) {
for (let j = 0; j < newDataLime.length; j++) {
if (features[i] === newDataLime[j].label) {
spanCounter ++
// Max 12 span by each line for ver
if(spanCounter == 12){
spanCounter = 0;
}
features[i] = `<span class="verbatim-dashboard__text__lime hide" style="background-color: ${newDataLime[j].rgba};">${features[i]}</span>`;
}
}
}
fieldText.innerHTML = fieldText.innerHTML + features.join(" ");
fieldText.innerHTML = fieldText.innerHTML + '<br>';
}
I would like every click to have the fieldText constant "empty" like the first call of some sort. I hope I have been clear enough.
Thank you in advance!
Change
fieldText.innerHTML = fieldText.innerHTML + features.join(" ");
to
fieldText.innerHTML = features.join(" ");
You are adding features to previous innerHTML. You set innerHTML to features not concat with existing innerHTML.
fieldText.innerHTML = features.join(" ") + '<br>';
Related
I have some javascript that I want to convert to jQuery...
How do we change javascript to jquery code?
Do we just change the document.getElementById > $?
Do we change document.querySelectorAll > $ too?
Does the function portion also need to be tweak?
Kindly see my code apprehend below:
// Home Page Gallery
let i = 0; // current slide
let j = 5; // total slides
const dots = document.querySelectorAll(".dot-container button");
const images = document.querySelectorAll(".image-container img");
function next() {
document.getElementById("content" + (i + 1)).classList.remove("active");
i = (j + i + 1) % j;
document.getElementById("content" + (i + 1)).classList.add("active");
indicator(i + 1);
}
function prev() {
document.getElementById("content" + (i + 1)).classList.remove("active");
i = (j + i - 1) % j;
document.getElementById("content" + (i + 1)).classList.add("active");
indicator(i + 1);
}
function indicator(num) {
dots.forEach(function (dot) {
dot.style.backgroundColor = "transparent";
});
document.querySelector(".dot-container button:nth-child(" + num + ")").style.backgroundColor = "#107e31";
}
function dot(index) {
images.forEach(function (image) {
image.classList.remove("active");
});
document.getElementById("content" + index).classList.add("active");
i = index - 1;
indicator(index);
}
// FAQ JS
let toggles = document.getElementsByClassName('toggle');
let contentDiv = document.getElementsByClassName('content');
let icons = document.getElementsByClassName('icon');
for(let i=0; i<toggles.length; i++){
toggles[i].addEventListener('click', ()=>{
if( parseInt(contentDiv[i].style.height) != contentDiv[i].scrollHeight){
contentDiv[i].style.height = contentDiv[i].scrollHeight + "px";
toggles[i].style.color = "#0084e9";
icons[i].classList.remove('fa-plus');
icons[i].classList.add('fa-minus');
}
else{
contentDiv[i].style.height = "0px";
toggles[i].style.color = "#111130";
icons[i].classList.remove('fa-minus');
icons[i].classList.add('fa-plus');
}
for(let j=0; j<contentDiv.length; j++){
if(j!==i){
contentDiv[j].style.height = "0px";
toggles[j].style.color = "#111130";
icons[j].classList.remove('fa-minus');
icons[j].classList.add('fa-plus');
}
}
});
}
When using $() with selectors, it's very similar to document.querySelectorAll().
So, if you wanted to query for a specific ID, you'd need to use a pound symbol # in front of the ID:
$('#some-id')
Really though, there's no reason I can think of these days to use jQuery. Additionally, you could probably remove the need for any of this JavaScript by simply using anchor fragments/hash and the :target selector. Your URLs could be like somepage.html#slide-1.
I want to create some HTML Elements of the same type with a for loop in JavaScript.
I wonder if I need to create a new Javascript variable for every element I want to show in the DOM or is it enought to override the same element again and again in my loop?
I wrote this code but it does only show one element as output:
let i;
for( i = 0; i < events.length; i++){
let tabElement = document.createElement("div");
tabElement.className = "tabElement";
tabElement.className = "ellipsis";
tabElement.id = "tabElement" + i;
tabElement.innerHTML = events[i].name;
let tabElementLink = document.createElement("a");
tabElementLink.className = "tabElementLink";
tabElementLink.id = "tabElementLink" + i;
$("tabElementLink").append(tabElement);
$(".tabBar").append(tabElementLink);
}
Than I wrote the following code but it this applies the same innerHTML to all returned elements.
let tabElements = {};
let tabElementsLink = {};
let i;
for( i = 0; i < events.length; i++){
tabElements['tabElement' + i] = document.createElement("div");
tabElements['tabElement' + i].className = "tabElement";
tabElements['tabElement' + i].className = "ellipsis";
tabElements['tabElement' + i].id = "tabElement" + i;
tabElements['tabElement' + i].innerHTML = events[i].name;
tabElementsLink['tabElementLink' + i] = document.createElement("a");
tabElementsLink['tabElementLink' + i].className = "tabElementLink";
tabElementsLink['tabElementLink' + i].id = "tabElementLink" + i;
tabElementsLink['tabElementLink' + i].append(tabElements['tabElement' + i]);
$(".tabBar").append(tabElementsLink['tabElementLink' + i]);
}
Which approach is right to generate multiple HTML elements from an array?
No metter, you can create every time new variable or rewrite. Better create variable every time.
your code can be optimized with new features and without any variables:
const events = [
{
name: "event1"
},
{
name: "event2"
},
{
name: "event3"
}
]
// if events is iterable
events.forEach((event, index)=>{
// for next lines, you forget href
$(".tabBar").append(`<div class="tabsElement ellipsis" id="tabelement${index}">${event.name}</div>`)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tabBar"></div>
And i don't think that you need any id at all, better to use data-id or something
The function displays eight elements on click in dynamically created divs using the slice() method. How can I give a unique id to each div? Your suggestions would be of great help to me.
var words = [40];
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++) {
x += '<div class=box>' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
x = "";
count += 8;
}
I have tried this but it's not working:
var mainDiv = document.getElementById('container');
var first = mainDiv.getElementsByTagName('div')[0];
first.id = 'one';
You can do it right inside the for loop while it's iterating:
for (i = 0; i < newArray.length; i++)
{
x += '<div id="box-' + i + '"> class="box">' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
You can use assign an ID inside the text string.
Here are a couple of other things you can do to improve this code:
Move the getElementById outside the loop
use js methods instead of string concatenation
Something like this (untested):
// get the container
container = document.getElementById('container');
for (i = 0; i < newArray.length; i++)
{
// create a div
var div = document.createElement('div');
// add attributes
div.setAttribute("id", "box-" + i);
div.setAttribute("class", "box");
// create text node
var textnode = document.createTextNode("This is div #" + i);
// add text to div
div.appendChild(textnode);
// append to container
container.appendChild(div);
}
How about giving it the id when creating? Also put the class=box in quotations like so -> class="box".
And add the whole div construct only once after the for loop. Because right now you are basically overwriting the whole thing multiple times.
var words = [40];
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++)
{
// Change class and add custom id
x += '<div class="box" id="box-'+i+'">' + newArray[i] + '</div>';
}
document.getElementById('container').innerHTML = x; // Add divs after for loop
x = "";
count += 8;
}
Now each box has a unique id going from box-0, box-1, ... to box-n
** I need new logics to store guessed letters in correct place. A game called hangman. As it is now the previous correct letter is overwritten if a new correct guess applys....**
function guessLetter() {
var letter;
var i;
var letterFound;
var correctLettersCount;
correctLettersCount=0;
letterBoxes = "";
letter = this.value;
for (i = 0; i < selectedWord.length; i++) {
if (selectedWord.charAt(i) == letter) { //if
letterBoxes += "<span>" + letter + "</span >";
}
else{
letterBoxes += "<span>*</span>";
}
document.getElementById("letterBoxes").innerHTML = letterBoxes;
}
}
You can use an array that will store the * and letters found
In the following snippet, this array is called display
const wordToFind = "testing";
const wordDisplay = document.getElementById("word");
let display = Array.from('*'.repeat(wordToFind.length));
wordDisplay.innerHTML = display.join("");
function checkLetter(el){
const letter = el.value.toLowerCase();
for(let i=0,l=wordToFind.length;i<l;i++){
if(wordToFind[i]===letter)
display[i] = letter;
}
el.value = "";
wordDisplay.innerHTML = display.join("");
}
<input oninput="checkLetter(this)" />
<p id="word"></p>
How to add space with continuously long string if there is no space in string after certain characters using JavaScript
For example string is
Helocsdnsajdnsajndjksandjks addwdwdwdnsajkkwfjnwkjqnf
wkjnfkjewnfefewfefewdd
and we want space after 10 characters
Result should be
Helocsdnsa jdnsajndjk sandjks addwdwdwdn sajkkwfjnw kjqnf wkjnfkjewn
fefewfefew dd
You can use /([^ ]{10})/g with .replace() method to add space after every 10 characters. Try this:
var str = "Helocsdnsajdnsajndjksandjks addwdwdwdnsajkkwfjnwkjqnf wkjnfkjewnfefewfefewdd";
str = str.replace(/([^ ]{10})/g, "$1 ");
console.log(str)
This can also do the job. If someone can do more customization to it, this code can help...
function SplitString(str, charLimit) {
var arrData = str.split(" ");
var returnStr = '';
if (arrData.length > 0)
{
for (var i = 0; i < arrData.length; i++)
{
if (arrData[i].length > charLimit)
{
var element = arrData[i];
var element2 = '';
var loopTimes = Math.ceil(arrData[i].length / charLimit);
var pickPlace = 0
for(var j = 0;j<loopTimes;j++)
{
if (j == (loopTimes - 1)) {
element2 = element2 + element.substring(pickPlace, element.length);
}
else
{
element2 = element2 + element.substring(pickPlace, (pickPlace + charLimit)) + ' ';
}
pickPlace = pickPlace + charLimit;
}
arrData[i] = element2;
}
}
for (var i = 0; i < arrData.length; i++)
{
returnStr = returnStr + arrData[i] + ' ';
}
returnStr = returnStr.substring(0,returnStr.length-1);
return returnStr;
}
}