How to replace numbers in a div? - javascript

With the following code, I'm getting the values of "id"(almost 35), and then add 1 to each "id", so 1 will be 2 and so on. Where I'm stock, it is on how to replace that id number in the html.
This is the code that use to get the values of each id, then I push them into an array, then I run another "for loop" to add 1 to each value, but I don't how to return them to the html.
var x = document.getElementsByClassName('p-divs');
var portfolio = new Array;
for (var i = 0; i < x.length; i++)
{
var y = document.getElementsByClassName('p-divs')[i].getAttribute('id');
portfolio.push(y);
}
console.log(portfolio);
var portfolio2 = new Array;
for (var i = 0; i<portfolio.length; i++)
{
var newId;
newId = parseInt(portfolio[i]) + 1;
portfolio2.push(newId);
}
console.log(portfolio2);
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 p-divs" id="1">
<div class="portfolio">
<center>
<img src="images/pace.png" width="230" height="190" alt="" class="img-responsive">
</center>
</div>
</div>

Since you're using jQuery library the code could be simple than what you've so far using .each() method :
$('.p-divs').each(function(){
$(this).attr('id', Number(this.id) + 1);
});
Or shorter using using .attr() method callback like :
$('.p-divs').attr('id', function(){
return Number(this.id) + 1;
});
The more clear version could be :
$('.p-divs').each(function(){
var current_id = Number(this.id); //Get current id
var new_id = current_id + 1; //Increment to define the new one
$(this).attr('id', new_id); //Set the new_id to the current element 'id'
});
Hope this helps.
$(function(){
$('.p-divs').attr('id', function(){
return Number(this.id) + 1;
});
//Just for Debug
console.log( $('body').html() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="p-divs" id="1">
<div class="portfolio">
<center>Image 1</center>
</div>
</div>
<div class="p-divs" id="2">
<div class="portfolio">
<center>Image 2</center>
</div>
</div>
<div class="p-divs" id="3">
<div class="portfolio">
<center>Image 3</center>
</div>
</div>
<div class="p-divs" id="4">
<div class="portfolio">
<center>Image 4</center>
</div>
</div>

Using native javascript, just use getattribute's opposite: setAttribute
for (var i = 0; i < x.length; i++)
{
var y = document.getElementsByClassName('p-divs')[i].getAttribute('id');
y++;
document.getElementsByClassName('p-divs')[i].setAttribute("id",y);
}

var j = document.getElementsByClassName('p-divs');
for (var i = 0; i < x.length; i++) {
j[i].id = portfolio2[i];
}
Add this to the end of your code. Vanilla JS.
j will be an array of your divs, i will keep count of which div we're on, and we are simply accessing the "id" of each element in the "j" array and updating it to the corresponding value in your pre-populated "portfolio2" array.
Hope this helps!
P.S.- I would also recommend that instead of using 'new Array' to instantiate your arrays, you use the array literal notation '[]'. This is more concise and also avoids needing to put (); after Array.

I'd suggest, assuming I'm not missing something, and that you're able to us ES6 methods:
// converting the NodeList returned from document.querySelectorAll()
// into an Array, and iterating over that Array using
// Array.prototype.forEach():
Array.from( document.querySelectorAll('.p-divs') ).forEach(
// using an Arrow function to work with the current element
// (divElement) of the Array of elements,
// here we use parseInt() to convert the id of the current
// element into a number (with no sanity checking), adding 1
// and assigning that result to be the new id:
divElement => divElement.id = parseInt( divElement.id, 10 ) + 1
);
Note that updating, changing or otherwise modifying an id shouldn't be necessary in most circumstances, and having a purely numeric id may present problems for CSS selecting those elements (it's valid, but only in HTML 5, but will still be problematic).

for(i=0;i<$('.p-divs').length;i++){
newId= parseInt($($('.p-divs')[i]).attr('id'))+1;
$($('.p-divs')[i]).attr('id',newId)
}
Using Jquery attr

Related

how to find out each index of a div

For example, I have
<div class="stick active"></div>
<div class="stick"></div>
<div class="stick"></div>
<div class="stick"></div>
<div class="stick"></div>
I need to find out all the indexes from the stick classes so that I can refer to each of them further [0],[1],[2]...
I tried to convert them to an array via [...] and via Array.prototype.slice.call
but when I try to interact with them, I get "undefined"
use this I think it will help you:
for first index:
var x = document.querySelectorAll(".stick");
console.log(x[0])
for all:
var x = document.querySelectorAll(".stick");
console.log(x)
Use Document.querySelectorAll() to create a NodeList.
querySelectorAll():
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
NodeList:
https://developer.mozilla.org/en-US/docs/Web/API/NodeList
const highlightedItems = document.querySelectorAll(".stick");
// access the second node:
console.log(highlightedItems[2].textContent);
// loop through all nodes
for (let i = 0; i < highlightedItems.length; i++) {
let item = highlightedItems[i];
console.log( item.id );
}
<div class="stick active"></div>
<div class="stick" id="1">A</div>
<div class="stick" id="2">B</div>
<div class="stick" id="3">C</div>
<div class="stick" id="4">D</div>
I think you want to hanle it via getElementsByClassName. This returns an HTML collection, not an array, thus you cannot use indexOf on it.
Iterating over the elements is the way to go, iterating over className, which is a string containing your node's class name, like this:
let stick = document.getElementsByClassName('stick');
for(let i=0; i < stick.length; i++){
console.log(stick[i]);
}

Creating a template out of HTML Elements

lets say i have a parent-div. And in this div-container, i want to display 5 elements which have all the same structure. For example:
<div class="element">
<p class="name">
</p>
<div class="logo">
</div>
</div>
Is there a way to make an object or prototype out of it, so i dont have to generate every single HTML Element with their classes and src values with the appendChild-function and Dot-Notations in a for-loop?
Im thinking of something like:
for(let i = 0; i<=5;i++){
var element = new element(class,src1,src2 ...);
}
And the "element" is defined in a external class file or something familiar.
Im a beginner, so please show mercy :)
You'll need to clone the node from the template's content. For example:
const templateElement = document.querySelector("#someTemplate")
.content
.querySelector(".element");
// create an Array of nodes (so in memory)
const fiveNodes = [];
for (let i = 0; i < 5; i += 1) {
const nwNode = templateElement.cloneNode(true);
// ^ clone the whole tree
nwNode.querySelector("p.name").textContent += ` #${i + 1}`;
fiveNodes.push(nwNode);
}
// append the nodes to document.body
// this is faster than appending every element in the loop
fiveNodes.forEach(el => document.body.append(el));
<template id="someTemplate">
<div class="element">
<p class="name">I am node</p>
<div class="logo"></div>
</div>
</template>

binding data to attribute by iterating

I have the following ForEach in my razor where i am setting some values.
It works fine. I can see my all values.
#foreach (var item in Model.ConsultantDetails.ScopeOfSevrices)
{
<div id="optionValue" class="item" data-value=>#item.Name</div>
}
Then i have an ajax call and get the result back.
I want to set this data back to same DIV by iterating
$.each(data.ConsultantDetails.ScopeOfSevrices, function (index) {
$('optionValue').attr("data-value=>", data.ConsultantDetails.ScopeOfSevrices[index].Name);
});
No luck, how do i achieve that?
use for loop instead of foreach, so we can set seprate id to each iteration
dont use data-value=> , instead use data-value=" " or some dummy value (here we use : item.Name)
#for (int i = 0; i < Model.ProductTypeService.Count; i++)
{
var item = Model.ProductTypeService[i];
var id = "optionValue" + i;
<div id="#id" class="item" data-value="#item.Name">#item.Name</div>
}
finally, in jquery, we can assign attribute value based on div id
$.each(data.ProductTypeService, function (index) {
$('#optionValue' + index).attr("data-value", data.ProductTypeService[index].Name + index); // + index // just to see different value
});

Adding get() to line causes "is not a function" error

This is the start of an inventory system I am working on. Basically it takes an array with items and quantities in a compressed form and outputs the items into an item div.
Running the below produces no error:
$('.item_amount').html(collection[itemName].amo);
Adding the get() method after the selector like so:
$('.item_amount').get(i).html(collection[itemName].amo);
produces "$(".item_amount").get(i).html is not a function".
This is what the line is altering:
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
The line that is causing the error is located in a for loop that loops through all the keys in an array. Then outputs the item quantity from the array in the item_amount div based on the index stored in the variable "i". The for loop also creates an object for each item in the array and puts in the a collection object.
Full code below:
<body>
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
<script type="text/javascript">
var collection = new Object();
function makeItem(itemName, id, amo) {
collection[itemName] = new item(id, amo);
}
function item(id, amo) {
this.id = id;
this.amo = amo;
}
var inventoryCom = "368.9,366.15,384.32"; //compressed inventory
var inventoryArr = inventoryCom.split(',');
for(var i=0; i < inventoryArr.length; i++) {
var itemName = 'item' + (i + 1); //unique name for each item
var itemArr = inventoryArr[i].split('.');
makeItem(itemName, itemArr[0], itemArr[1]);
$('.item_amount').get(i).html(collection[itemName].amo);
}
</script>
</body>
.get(i) returns DOM element, which doesn't have .html() method - that's what js engine wants to say to you.
You need to use .eq(i) instead. Like
$('.item_amount').eq(i).html(collection[itemName].amo);
or
$('.item_amount:eq(' + i + ')').html(collection[itemName].amo);
This line may be a problem
var itemName = 'item' + (i + 1); //
This may increment the array count out of the upper bound. check the itemName value.
Also try to add an alert for this
collection[itemName].amo

How to get the count of the DIVs with almost the same ID property?

I have many DIVs on my page with the same ID
eg:
<div id="myDiv1">
...
</div>
<div id="myDiv2">
...
</div>
<div id="myDiv3">
...
</div>
...
<div id="myDiv20">
...
</div>
...
As You see, the ID property looks almost the same - the only diffrence is that there is a number in each ID.
How to get the count of that DIVs? I thought I can do something like that:
var myDivs= document.getElementById('myDiv');
but returns null
You can do this using jQuery like this:
$('div[id^=myDiv]')
If you can't use jQuery, you'll need to call getElementsByTagName and loop through the values checking the ID property.
var divs = document.getElementsByTagName('div');
var counter = 0;
for(var i in divs) {
if(divs[i].id.indexOf('myDiv') === 0) {
counter++;
}
}
or just
document.querySelectorAll('[id^=myDiv]').length
you can use jquery
//this will give you all divs start with myDiv in the id
var divs = $("div[id^='myDiv']");
From this site:
function getElementsByRegExpId(p_regexp, p_element, p_tagName) {
p_element = p_element === undefined ? document : p_element;
p_tagName = p_tagName === undefined ? '*' : p_tagName;
var v_return = [];
var v_inc = 0;
for(var v_i = 0, v_il = p_element.getElementsByTagName(p_tagName).length; v_i < v_il; v_i++) {
if(p_element.getElementsByTagName(p_tagName).item(v_i).id && p_element.getElementsByTagName(p_tagName).item(v_i).id.match(p_regexp)) {
v_return[v_inc] = p_element.getElementsByTagName(p_tagName).item(v_i);
v_inc++;
}
}
return v_return;
}
Usage:
var v_array = getElementsByRegExpId(/^myDiv[0-9]{1,2}/);

Categories