How to print array in order have same class name div - javascript

How to print array in order have same class name div. i try this code but it was print the same value of the last array. have any other way to do this
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(e) {
var sss = '5#45#41#25#65';
var full = sss.split('#');
var mainid = full[0];
var full_sub = full[1].split('#');
var sub_count = full_sub.length;
alert(sub_count);
for(var i=0;i<sub_count;i++)
{
$(".block").attr(data-id,full_sub[i]);
$(".block").html(full_sub[i]);
}
});
</script>
<div class="block" data-id="" ></div>
<div class="block" data-id="" ></div>
<div class="block" data-id="" ></div>
<div class="block" data-id="" ></div>

Try
$(".block").each(function(index)
{
$(this).attr("data-id",full_sub[index]);
$(this).html(full_sub[index]);
});
In your code, each time you are assigning the html() to whole elements with the class .block. Here the html() is assigned to each tags with the same class name.
Also you forgot to put data-id in "". Otherwise it will take it as a variable, which causes the error..

Your current code overwrites all of the elements with the class of block in each loop iteration. Instead, create a parent element and append elements:
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(e) {
var sss = '5#45#41#25#65';
var full = sss.split('#');
var mainid = full[0];
var full_sub = full[1].split('#');
var sub_count = full_sub.length;
alert(sub_count);
var parent = document.querySelector('#parent');
for(var i=0;i<sub_count;i++)
{
var div = document.createElement('div');
div['data-id'] = full_sub[i];
div.textContent = full_sub[i];
parent.appendChild(div);
}
});
</script>
<div id="parent"></div>
Working JSFiddle

If you do that way it will always print the same value of the last array.
You should use JQuery append function to append block div into a wrap div.
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(e) {
var sss = '5#45#41#25#65';
var full = sss.split('#');
var mainid = full[0];
var full_sub = full[1].split('#');
var sub_count = full_sub.length;
alert(sub_count);
for(var i=0;i<sub_count;i++)
{
$("#wrapBlock").append('<div class="block" data-id="'+ full_sub[i] +'">'+ full_sub[i] +'</div>');
}
});
</script>
<div id="wrapBlock"></div>
That's my solution, hopefully it's helpful!

Try this.
HTML
<div class="block" ></div>
<div class="block" ></div>
<div class="block" ></div>
<div class="block" ></div>
Script
var sss = '5#45#41#25#65',
full = sss.split('#'),
full_sub = full[1].split('#');
$('.block').each(function(index){
$(this).attr('data-id', full_sub[index]);
$(this).html(index+1);
});
Fiddle Demo

The problem is that when you call $(".block").html(full_sub[i]);, you are setting it on all the divs with class .block; By doing the loop, you overwrite them each time and once you get out of the loop, they are set to the last value
Anoop's code works, an alternative is
var blocks = $(".block");
for(var i=0;i<sub_count;i++)
{
$(blocks[i]).attr('data-id',full_sub[i]);
$(blocks[i]).html(full_sub[i]);
}
The trick is that you can get at each of the items in jQuery's collection by using obj[intIndex] so that you're not dealing with all of them.
The each method is the jQuery way of doing it, it will iterate through each of the elements in the jQuery object, passing it the index, and this will point to the element being iterated
$(".block").each(function(index) {
$(this).attr("data-id",full_sub[index]);
$(this).html(full_sub[index]);
});

Related

how to add multiple "actual" element objects in JQuery selector

I am working on Google Apps Script and using JQuery. I want to put multiple actual elements in the JQuery selector. I want to put actual elements in the selector.
I want:
$(kojiNameElem, tankaElem, suryoElem, unitElem)
not like(it works though):
$(".kojiName, .tanka, .suryo, .unit")
Please see this code followed:
var kojiNameElem = $("#koji_"+koji_id).find(".kojiName");
var tankaElem = $("#koji_"+koji_id).find(".tanka");
var suryoElem = $("#koji_"+koji_id).find(".suryo");
var unitElem = $("#koji_"+koji_id).find(".unit");
$(kojiNameElem, tankaElem, suryoElem, unitElem).on("focusin",function(e) {
console.log("focusin");
});
It works only on kojiNameElem. The other elements don't.
I know it works with one single element in the JQuery selector as below.
$(kojiNameElem).on("focusin",function(e) {
console.log("focusin");
});
Could you help me please?
You can do it like
var koji_id=1;
var kojiNameElem = $("#koji_"+koji_id).find(".kojiName");
var tankaElem = $("#koji_"+koji_id).find(".tanka");
var suryoElem = $("#koji_"+koji_id).find(".suryo");
var unitElem = $("#koji_"+koji_id).find(".unit");
$("#koji_"+koji_id).on("click", '.kojiName,.tanka,.suryo,.unit',function(e) {
console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="koji_1">
<span class="kojiName">kojiName</span>
<span class="tanka">tanka</span>
<span class="suryo">suryo</span>
<span class="unit">unit</span>
</div>
You can also use add method
var koji_id=1
var koji= $("#koji_"+koji_id);
var kojiNameElem = koji.find(".kojiName");
var tankaElem = koji.find(".tanka");
var suryoElem = koji.find(".suryo");
var unitElem = koji.find(".unit");
$(kojiNameElem).add(tankaElem).add(suryoElem).add(unitElem).on("click",function(e) {
console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="koji_1">
<span class="kojiName">kojiName</span>
<span class="tanka">tanka</span>
<span class="suryo">suryo</span>
<span class="unit">unit</span>
</div>
There's no way to combine multiple jquery objects in a single selector - the method to do this is .add()
Demonstration:
var a = $("#a");
var b = $("#b");
var c = $("#c");
var arr = a.add(b).add(c).map((i, e)=>$(e).text()).toArray();
console.log(arr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="a">a</div>
<div id="b">b</div>
<div id="c">c</div>

Deleting the last Element in a Div [JavaScript]

I'm having a strange problem. I'm trying to make a program that will add and delete div's inside another div called "body". To add divs, I use document.getElementById("body").innerHTML. Adding works fine. However, in the deleting function, I replace the "body" id with a variable with the id of the div that will be deleted. But when I run the code, I get the error "cannot set innerHTML of null". I tried to replace the id variable with a fixed local variable, and it worked fine. I also tried to add quotes to the variable but that didn't work either. Is there any reason why I can't set the id to a changing variable? Thanks.
Here is my code:
var i = 1;
function myFunction() {
var addDiv = document.getElementById("body2");
addDiv.innerHTML += "<div id = '" + i + "'><br><textarea id = '1' > foo < /textarea></div > ";
i++;
}
function myFunction2() {
var deleteDiv = document.getElementById(i);
deleteDiv.innerHTML = "";
i--;
}
<div id="body2">
<div id="0">
<textarea id="text">lol</textarea><button onclick="myFunction()">Add</button>
<button onclick="myFunction2()">Delete</button>
</div>
</div>
you are incrementing i after adding a div so you must use i-1 while deleting to get correct id.
var i = 1;
function myFunction() {
var addDiv = document.getElementById("body2");
addDiv.innerHTML += "<div id = '"+i+"'><br><textarea id = '1'>foo</textarea></div>";
i++;
}
function myFunction2() {
var deleteDiv = document.getElementById(i-1);
deleteDiv.remove();
i--;
}
<div id = "body2">
<div id = "0">
<textarea id = "text">lol</textarea><button onclick =
"myFunction()">Add</button>
<button onclick = "myFunction2()">Delete</button>
</div>
</div>
To remove last child, you can even use CSS selector last-child. You should also add specific class to newly added divs as you would want to remove only newly added divs.
This will also remove dependency of i.
As an addon, you can also use document.createElement + Node.appendChild instead of setting innerHTML. .innerHTMl will be expensive for highly nested structure.
function myFunction() {
document.getElementById("body2").appendChild(getDiv());
}
function getDiv(i){
var div = document.createElement('div');
div.classList.add('inner')
var ta = document.createElement('textarea');
ta.textContent = 'foo';
div.appendChild(ta);
return div;
}
function myFunction2() {
var div = document.querySelector('#body2 div.inner:last-child')
div && div.remove()
}
<div id="body2">
<div id="0">
<textarea id="text">lol</textarea><button onclick="myFunction()">Add</button>
<button onclick="myFunction2()">Delete</button>
</div>
</div>
You can refer "innerHTML += ..." vs "appendChild(txtNode)" for more information.

replace set of strings in array

Using $('div#top_container').html(), I get the following as an example:
<div class="top" id="top_container">
<div class="example">First</div>
<div class="example">Second</div>
</div>
giving...
<div class="example">First</div>
<div class="example">Second</div>
Here, using .replace(), I want to replace <div class="example"> with *%^% (random set of characters) and remove </div>:
var content = $('div#top_container').html();
var clean_1 = content.replace('<div class="example">','*%^%'); //add $*!#$
var clean_2 = clean_1.replace('</div>',' '); //remove </div>
giving...
console.log(clean_2); --> *%^%First*%^%Second
Now, the number of example div elements can vary and I need to first find out how to target them all. Also is there a cleaner way to target both <div class="example"> and </div> at the same time?
EDIT:
I am not looking to change the html itself, but rather have the edited version as a variable that I can do stuff with (such as send it to php via ajax).
How would I do this?
Use replaceWith() method with a callback and generate prefered text string by getting text content using text() method.
$('div.example').replaceWith(function(v) {
return '%^%' + $(this).text();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="example">First</div>
<div class="example">Second</div>
</div>
UPDATE: If you don't want to update the original element then use clone() and do the remaining thinks on the cloned element.
var res = $('#parent')
// clone element
.clone()
// get element with `example` class
.find('.example')
// update content
.replaceWith(function(v) {
return '%^%' + $(this).text();
})
// back to previos selector and get html content
.end().html();
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div class="example">First</div>
<div class="example">Second</div>
</div>
Create one prototype like :
String.prototype.replaceAll = function (toReplace, replaceWith){
return this.split(toReplace).join(replaceWith);
}
and your jquery code be like :
$("div#top_container").each(function( i ) {debugger;
console.log(this.innerHTML.replaceAll('<div class="example">','*%^%').replaceAll('</div>',' ');)
});
You can use replaceWith function
$(function () {
$(".example").replaceWith(function(){
return "%^%"+$(this).text();
});
});
You can make a clone of container if you don't want to change original div.
var html="";
$(function () {
var newHtml = $("#top_container").clone();
$(newHtml).find(".example").replaceWith(function () {
html+= "%^%" + $(this).text();
});
});
console.log(html);

How to use a Javascript var as an ID for a div?

What I have is a function that that generates string that get stored into a javascript var. What I want to do with that the var is assign it to be an id for a div on a page. I've been trying to get the variable set as the div ID but I have some difficulty in doing so.
<script>
var rand = "arandomstring"
</script>
<div id= $(rand) class = "outline">
<b>Some Sample Text</b><br>
</div>
Am I assigning the variable correctly? It seems that this makes the div id = "$(rand)" rather than "arandomstring".
Any help would be appreciated.
The code below will assign the value of the variable "rand" to your div's ID
HTML Code:
<div name="arandomstring" class="outline">
<b>Some Sample Text</b></br>
<div>
Javascript
<script>
var rand = 'some_data';
$(".arandomstring").attr("id", rand);
</script>
You cannot put JavaScript inside most attributes in HTML - only the onevent attributes (e.g. onclick="", onmouseover="") and href="" (with the javascript: URI scheme).
Instead, use an initial id="" value:
<div id="temp" class="outline"><b>some sample text</b></div>
var rand = getNewId();
var div = document.getElementById("temp");
div.setAttribute("id", rand);
Quotes are optional, so id= $(rand) translates to id= "$(rand)".
Also, you don't give Javascript in markup unless it is an event attribute like onclick, etc or href.
You can do
<div class = "outline">
<b>Some Sample Text</b><br>
</div>
<script>
var rand = "arandomstring";
document.querySelector(".outline").id = rand;
alert(document.documentElement.innerHTML);
</script>
From what I see looks like you are using jQuery. Here is how you assign this variable as an id:
<script>
var rand = "arandomstring";
$('.outline').attr('id', rand);
</script>
<div class="outline">
<b>Some Sample Text</b><br>
</div>
Fiddle: https://jsfiddle.net/Smartik/waoecL2a/

Can't insert a div into another internal div

I need your help to solve a problem I have.
I have this code:
<div id="div1" >
<div id="edit1">
hello
<input type="button" id="b1" onclick="aaa()"/>
</div>
</div>
I want to use insert into the internal div (id=edit1) another new div I generated.
I tried alike code but it's not running:
js:
function aaa()
{
var elem = createDivLine();
var el1 = document.getElementById("div1");
var el2 = el1.getElementById("edit1");
el2.appendChild(elem);
}
function createDivLine()
{
var tempDiv1 = document.createElement("div");
tempDiv1.innerHTML = "Sam";
return tempDiv1;
}
The result should looks like this:
<div id="div1" >
<div id="edit1">
hello
<input type="button" id="b1" onclick="createDivTable()"/>
<div>"Sam"</div>
</div>
</div>
JSFiddle: http://jsfiddle.net/KknXF/
Since IDs are unique, it is not valid to attempt to get an element's children by ID.
Remove this line:
var el1 = document.getElementById('div1');
And change the following line to:
var el2 = document.getElementById('edit1');
In the event that you have some irrepairably (I can never spell that word...) broken HTML that you can't possibly change, try this:
var el2 = document.querySelector("#div1 #edit1");
It should be
function aaa() {
var elem = createDivLine();
var el2 = document.getElementById("edit1");
el2.appendChild(elem);
}
Demo: Fiddle

Categories