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

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>

Related

Change text of element for each element that have the same class in jQuery

So, I'm trying to only show certain part of the text. The info is passed like this. Ex: ["PS4"] and I only want the PS4 text to show so I did this with jQuery:
var text = $('.gender').text();
var text2=text.substring(text.indexOf('"')+1,text.lastIndexOf('"'));
$('.gender').text(text2);
The problem is that I want to change every single element text that have .gender class but only having their corresponding text, like so:
["PS4"]["XBOX"]
<div class="gender">PS4</div><div class="gender">XBOX</div>
I tried to do it with .each() function but I got something like this:
<div class="gender">PS4"]["XBOX</div><div class="gender">PS4"]["XBOX</div>
Here's the code with jQuery .each():
$('.gender').each(function(){
var text = $('.gender').text();
var text2=text.substring(text.indexOf('"')+1,text.lastIndexOf('"'));
$('.gender').text(text2);
});
EDIT:
I have an HTML with this:
<div class="gender">["PS4"]</div>
<div class="gender">["XBOX"]</div>
So I want to remove the '[""]' from every element that have .gender class so it shows like this:
<div class="gender">PS4</div>
<div class="gender">XBOX</div>
Use $(this) and not $(".gender")
$('.gender').each(function() {
var text = $(this).text();
var text2 = text.substring(text.indexOf('"') + 1, text.lastIndexOf('"'));
$(this).text(text2);
});
demo
$('.gender').each(function() {
var text = $(this).text();
var text2 = text.substring(text.indexOf('"') + 1, text.lastIndexOf('"'));
$(this).text(text2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gender">["PS4"]</div>
<div class="gender">["XBOX"]</div>
You may go for RegEx, with $.text(callback)
$(function() {
$('.gender').text(function() {
return $(this).text().replace(/^\[\"(.*)\"\]$/, '$1');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gender">["PS4"]</div>
<div class="gender">["XBOX"]</div>
Breakup of, ^\[\"(.*)\"\]$ as below:
^ starts with
(.*) group having any match of any length
$ ends with
Try this one also:
$('.gender').each(function() {
var text = $(this).text();
var text2 = text.replace("\"]", "");
text2 = text2.replace("[\"", "");
$(this).text(text2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gender">["PS4"]</div>
<div class="gender">["XBOX"]</div>

How to append a text or number range to a div using javascript?

I inherited a JS file that goes like this:
var id1 = document.getElementById("id1");
var id2 = document.getElementById("id2");
var id3 = document.getElementById("id3");
var id4 = document.getElementById("id4"); //etc etc.
I was wondering if there is an easier way using plain Javascript to append a number to an id that has the same name, rather than listing each one out line by line.
Please advise.
Thanks!
var nodes = [];
var find = 6;
for (var i = 1; i <= 6; i++) {
nodes.push(document.getElementById('id' + i));
}
console.log(nodes);
<div id="id1"></div>
<div id="id2"></div>
<div id="id3"></div>
<div id="id4"></div>
<div id="id5"></div>
<div id="id6"></div>
A more robust solution:
Use querySelectorAll to select elements that have id's that begin with id, then filter out the results that do not match id followed by a number.
var nodes = document.querySelectorAll('[id^="id"]');
nodes = [].slice.call(nodes).filter(function(node) {
return /id\d+/.test(node.id);
});
console.log(nodes);
<div id="id1"></div>
<div id="id2"></div>
<div id="id3"></div>
<div id="id4"></div>
<div id="id5"></div>
<div id="id6"></div>
<!-- This node should not be included -->
<div id="idea"></div>

Extract a part of an id

I've got multiple divs with ids. I need to remove a certain part of a div ID and get it onto a variable. How can I do this? example:
<div id="fruitapple14754"></div>
<div id="fruitapple1564"></div>
<div id="fruitapple14"></div>
I need to remove fruitapple1 from the id and get the remaining part assigned to a variable. The length of fruitapple1 is always the same.
You can get an array of all the IDs like this:
var collection = [];
$('[id^="fruitapple"]').each(getId);
function getId() {
var id = $(this).attr('id').split('fruitapple1').pop();
collection.push(id);
}
You can use substr for this here is how to use:-
var ids=[];
$('[id^="fruitapple"]').each(function(){
var id=$(this).attr('id');
ids.push(id.substr(11));
});
alert(JSON.stringify(ids));
Demo
The simplest way would be to replace it with an empty string
$('[id^="fruitapple"]').each(function() {
var subId = $(this).attr('id').replace('fruitapple1', '');
console.log(subId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="fruitapple14754"></div>
<div id="fruitapple1564"></div>
<div id="fruitapple14"></div>
You can use .substring() method of javascript.
Check out this fiddle.
Here is the snippet.
var divs = document.getElementsByTagName('div');
for (i = 0; i < divs.length; i++) {
var id = divs[i].id;
alert(id.substring(11)); // length of 'fruitapple1' = 11
}
<div id="fruitapple14754"></div>
<div id="fruitapple1564"></div>
<div id="fruitapple14"></div>
Try to use startwith selector,
$('[id^="fruitapple1"]').each(function() {
console.log(this.id.replace('fruitapple1', ''));
});
If you want to get it into an array variable then use map() like
console.log($('[id^="fruitapple1"]').map(function() {
return (this.id.replace('fruitapple1', ''));
}).get());
console.log($('[id^="fruitapple1"]').map(function() {
return (this.id.replace('fruitapple1', ''));
}).get());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fruitapple14754"></div>
<div id="fruitapple1564"></div>
<div id="fruitapple14"></div>
A simple answer using substring as suggested in my comment. I'm on mobile that's why it took long.
var idSubstring = document.getElementById("yourIdHere").id.substring(11);
alert(idSubstring);
Demo JSFiddle

How to print array in order have same class name div

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]);
});

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