JavaScript Get Selected Item's TextContent - javascript

I want to make a program that write out the textContent of the item that has clicked. For some reason this program only get the last element's content. Any idea what should I change inside the for loop?
var emailname = document.querySelectorAll(".name");
var gSenderName = document.getElementById('sname');
$('.name').click(function() {
for (var i = 0; i < emailname.length; i++) {
const sendername = emailname[i].textContent;
gSenderName.textContent = sendername;
}
});
.name:hover {
text-decoration: underline;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">first</div><br>
<div class="name">second</div><br>
<div class="name">third</div>
<br>
<div>Selected:
<div id="sname"></div>
</div>

You do not need the loop here at all. You can simply get the currently clicked element's text by using this object. I will also suggest you not mix up vanilla JS and jQuery unnecessarily:
var gSenderName = $('#sname');
$('.name').click(function(){
gSenderName.text($(this).text());
});
.name:hover {
text-decoration: underline;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">first</div><br>
<div class="name">second</div><br>
<div class="name">third</div>
<br>
<div>Selected:
<div id="sname"></div>
</div>

The loop runs and sets the text content of each item one after the other. Because each override the other, you always get the last one.
Just set the text content of the element that was clicked:
var gSenderName = document.getElementById('sname');
$('.name').click(e => {
gSenderName.textContent = e.target.textContent;
});
.name:hover {
text-decoration: underline;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">first</div><br>
<div class="name">second</div><br>
<div class="name">third</div>
<br>
<div>Selected:
<div id="sname"></div>
</div>

Related

Javascript on click event for multiple buttons with same class

I have a few buttons across a site I am building, certain buttons have one class while others have another. What I am trying to do is find the best way to find the clicked button without having an event listener for each individual button. I have come up with the below 2 for loops to find all the buttons with class button-1 and class button-2. Being fairly new to javascript i just don't want to get into bad habits so would appreciate any advice on the best way to achieve this.
<section>
<div class="button--1"></div>
<div class="button--1"></div>
<div class="button--2"></div>
</section>
<section>
<div class="button--2"></div>
<div class="button--1"></div>
<div class="button--2"></div>
</section>
var button1 = document.querySelectorAll('.button--1');
var button2 = document.querySelectorAll('.button--2');
for (var a = 0; a < button1.length; a++) {
button1[a].addEventListener('click',function(){
//do something
});
}
for (var b = 0; b < button2.length; b++) {
button1[b].addEventListener('click',function(){
//do something
});
}
If you plan to have multiple other classes like button--3, …4 … …15,
You must want to target all div elements which class starts (^=) with "button":
(Note that you can do it in the CSS too!)
var allButtons = document.querySelectorAll('div[class^=button]');
console.log("Found", allButtons.length, "div which class starts with “button”.");
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener('click', function() {
console.clear();
console.log("You clicked:", this.innerHTML);
});
}
/* Some styling */
section {
margin: 8px 0;
border: 1px solid gray;
}
section div {
border: 1px solid lightgray;
display: inline-block;
margin-left: 8px;
padding: 4px 8px;
width: 30px;
}
section div[class^=button] {
background: lightgray;
cursor: pointer;
}
<span>You can click on the buttons:</span>
<section>
<div class="button--1">s1-1</div>
<div class="button--2">s1-2</div>
<div class="button--3">s1-3</div>
<div class="button--4">s1-4</div>
</section>
<section>
<div class="button--1">s2-1</div>
<div class="button--2">s2-2</div>
<div class="button--3">s2-3</div>
<div class="button--4">s2-4</div>
</section>
<section>
<div class="not-a-button">not1</div>
<div class="not-a-button">not2</div>
<div class="not-a-button">not3</div>
<div class="not-a-button">not4</div>
</section>
Hope it helps.
Try using event delegation
(function() {
document.body.addEventListener("click", clickButtons);
// ^ one handler for all clicks
function clickButtons(evt) {
const from = evt.target;
console.clear();
if (!from.className || !/button--\d/i.test(from.className)) { return; }
// ^check if the element clicked is one of the elements you want to handle
// if it's not one of the 'buttons', do nothing
console.log("you clicked " + from.classList);
}
}())
.button--1:before,
.button--2:before {
content: 'BTTN['attr(class)']';
}
.button--1,
.button--2 {
border: 1px solid #999;
background: #eee;
width: 220px;
padding: 3px;
text-align: center;
}
<section>
<div class="b1 button--1 section1"></div>
<div class="b2 button--1 section1"></div>
<div class="b3 button--2 section1"></div>
</section>
<section>
<div class="b4 button--2 section2"></div>
<div class="b5 button--1 section2"></div>
<div class="b6 button--2 section2"></div>
</section>
You can use multiple selectors in the string of querySelctorAll() by separating them with a ,
var button1 = document.querySelectorAll('.button--1');
var button2 = document.querySelectorAll('.button--2');
var allButtons = document.querySelectorAll('.button--1, .button--2');
console.log(button1.length);
console.log(button2.length);
console.log(allButtons.length);
<section>
<div class="button--1"></div>
<div class="button--1"></div>
<div class="button--2"></div>
</section>
<section>
<div class="button--2"></div>
<div class="button--1"></div>
<div class="button--2"></div>
</section>
My suggestion is to use jQuery so that you can do it something like this:
$(document).on('click', '.button--1', function() {
// Do something
});
$(document).on('click', '.button--1', function() {
// Do something
})
But a clean approach for pure Javascript is to create a function that binds a callback for the event.
function bindEvent(callback, eventType, targets) {
targets.forEach(function(target) {
target.addEventListener(eventType, callback);
});
};
var button1 = document.querySelectorAll('.button--1');
var button2 = document.querySelectorAll('.button--2');
bindEvent(function() {
// do something
}, 'click', button1);
bindEvent(function() {
// do something
}, 'click', button2);
The click event is fired when a pointing device button (usually a mouse's primary button) is pressed and released on a single element.
This documentation will help you to understand how it works MDN - Click event

How to clone, modify (increment some elements) before appending using jQuery?

I have an element that contains multiple elements inside it, what I need is to clone the element, but on every "new" element, I need to increment an element (the object number -see my script please-)
In the script I'm adding I need (every time I click on the button) to have : Hello#1 (by default it's the first one) but the first click make : Hello#2 (and keep on top Hello#1) second click = Hello#1 Hello#2 Hello#3 ... We need to keep the oldest hellos and show the first one.
var count = 1;
$(".button").click(function(){
count += 1;
num = parseInt($(".object span").text());
$(".object span").text(count);
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
cont.append(div);
});
.object{
width:100px;
height:20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
You just have to change a little:
var count = 1;
$(".button").click(function() {
count += 1;
num = parseInt($(".object span").text());
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
div.find('span').text(count); // <------here you have to put the count
cont.append(div);
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
and if you want to simplify this more use this:
$(".button").click(function() {
var idx = ++$('.object').length; // check for length and increment it with ++
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
div.find('span').text(idx); // <------here you have to put the count
cont.append(div);
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
Use the following function, this is more modular and you can use it to update the count if you remove one of the elements
function updateCount() {
$(".object").each(function(i,v) {
$(this).find("span").text(i+1);
});
}
$(".button").click(function() {
num = parseInt($(".object span").text());
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
cont.append(div);
updateCount();
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>

Add class to an element without an id

I have a list of items:
<div class="crew-item>
<div class="crew-grid"></div>
<div class="crew-detail></div>
</div>
<div class="crew-item>
<div class="crew-grid"></div>
<div class="crew-detail></div>
</div>
<div class="crew-item>
<div class="crew-grid"></div>
<div class="crew-detail></div>
</div>
When I click on a selected 'crew-grid' I'd like to add a class ('active') to its 'crew-item' parent, but I have no idea how to achieve that using vanilla js or jQuery.
The goal is to reveal the 'crew-detail' part, with active class added to its parent.
Like this?:
$('.crew-grid').on('click', function () {
$(this).closest('.crew-item').addClass('active');
});
Basically, starting from the clicked element, get the closest ancestor element which matches that selector. You don't need an id to target an element, just a way to identify it based on the information you have (in this case the clicked element).
If you want to de-activate other elements at the same time:
$('.crew-grid').on('click', function () {
$('.crew-item').removeClass('active');
$(this).closest('.crew-item').addClass('active');
});
Using jQuery :
$('.crew-grid').click(function() {
$(this).closest('.crew-item').addClass('active');
});
Use Document.querySelectorAll()
var crews = document.querySelectorAll('.crew-item');
if (crews) {
for (var i = 0; i < crews.length; i++) {
var grid = crews[i].querySelector('.crew-grid');
grid.addEventListener('click', toggleActive, false);
}
}
function toggleActive() {
var grids = document.querySelectorAll('.crew-item');
for (var i = 0; i < grids.length; i++) {
if (grids[i].classList.contains('active')) {
grids[i].classList.remove('active');
}
}
this.parentNode.classList.add('active');
}
.crew-item.active {
background: #DDD;
}
.crew-grid:hover {
cursor: pointer;
background: #eee;
}
<div class="crew-item active">
<div class="crew-grid">crew-grid</div>
<div class="crew-detail">crew-detail</div>
</div>
<br>
<div class="crew-item">
<div class="crew-grid">crew-grid</div>
<div class="crew-detail">crew-detail</div>
</div>
<br>
<div class="crew-item">
<div class="crew-grid">crew-grid</div>
<div class="crew-detail">crew-detail</div>
</div>

How to target individual div & apply class or attribute id

How can i select each div inside parent div & apply class (om_0 & go on) with increasing index number. Here I am unable to target each div.
Or how can I add attribute id="om_0", id="om_1", id="om_2" etc. to each div
The problem is it's applying all classes in one div & repeat it
var cirLength = $("div#circleBox > div").length;
for(var i=0; i<cirLength; i++){
$("div#circleBox").find('div').addClass('om_'+i);
}
<div id="circleBox"><div class="om_0 om_1 om_2"><span>AcessGreen</span></div><div class="om_0 om_1 om_2"><span>AccessBlue</span></div><div class="om_0 om_1 om_2"><span>AccessOrange</span></div></div>
You can use each() to iterate jQuery objects
$("div#circleBox").find('div').each(function(i) {
$(this).addClass('om_' + i);
// If you need to add it as id then use `this.id= 'om_' + i ` instead of `$(this).addClass('om_' + i)`
});
.om_0 {
color: red;
}
.om_1 {
color: green;
}
.om_2 {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="circleBox">
<div><span>AcessGreen</span>
</div>
<div><span>AccessBlue</span>
</div>
<div><span>AccessOrange</span>
</div>
</div>
With your own code you need to select individual item using eq()
var cirLength = $("div#circleBox > div").length;
for (var i = 0; i < cirLength; i++) {
$("div#circleBox").find('div').eq(i).addClass('om_' + i);
}
.om_0 {
color: red;
}
.om_1 {
color: green;
}
.om_2 {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="circleBox">
<div><span>AcessGreen</span>
</div>
<div><span>AccessBlue</span>
</div>
<div><span>AccessOrange</span>
</div>
</div>

Change child element of array item (syntax)

I have a few divs which are using the same class.
Inside the divs are three more divs with identical classes.
<div class="plane">
<div class="win1">Lorem ipsum</div>
<div class="win2">Dolor sit</div>
<div class="win3">amet.</div>
</div>
<div class="plane">
<div class="win1">Lorem ipsum</div>
<div class="win2">Dolor sit</div>
<div class="win3">amet.</div>
</div>
var allPlanes = $('.plane');
for (var i = 0; i < allPlanes.length; i++) {
var onePlane = allPlanes[i];
var baseHeight = 10;
$(onePlane + " .win1").css("height", parseInt(baseHeight*1));
$(onePlane + " .win2").css("height", parseInt(baseHeight*2));
$(onePlane + " .win3").css("height", parseInt(baseHeight*3));
}
(Don't mind about the names. It's just an example...)
Now I made an array with the outside divs and I can select the single divs inside. But I did not get the right syntax for the child divs inside.
Can anyone help?
My Fiddle: http://jsfiddle.net/SchweizerSchoggi/559xvww6/
Change you script to this:
var allPlanes = $('.plane');
var baseHeight = 10;
$(".plane > .win1").css("height", parseInt(baseHeight*1)+"px");
$(".plane > .win2").css("height", parseInt(baseHeight*2)+"px");
$(".plane > .win3").css("height", parseInt(baseHeight*3)+"px");
You don't need the for loop in such a case.
A prettier way:
var baseHeight = 10;
for (var i = 1; i <= 3; i++) {
$(".plane > .win"+i).css("height", parseInt(baseHeight*i)+"px");
}
http://jsfiddle.net/559xvww6/3/
If you don't want to use a for loop and want to dinamically configure from an array:
var baseHeight = 10;
$.map([1,2,3], function(i) {
$(".plane > .win"+i).css("height", parseInt(baseHeight*i)+"px");
});
http://jsfiddle.net/559xvww6/10/
Edit:: Just a side note: all these approachs are valid, but that doesn't mean that they are the best / most efficient ones. Feel free to use the one you like the most, understand it and try to use it or adapt it to your very personal situation. The "easiest" approach is surely the first one, but it is also the longest one.
isn't this one is better:
var base = 10;
$('.plane > div').css('height', function(){
return base*($(this).index()+1)
});
.plane {
background-color: #ccc;
border: solid 1px #cdcdcd;
margin-bottom: 15px;
}
.plane > .win1 { background-color: #ddd; }
.plane > .win2 { background-color: #eee; }
.plane > .win3 { background-color: #fff; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="plane">
<div class="win1">Lorem ipsum</div>
<div class="win2">Dolor sit</div>
<div class="win3">amet.</div>
</div>
<div class="plane">
<div class="win1">Lorem ipsum</div>
<div class="win2">Dolor sit</div>
<div class="win3">amet.</div>
</div>
You cannot use + operator between a jQuery object and a string.
The correct way to do it is this:
$(".win1", onePlane).css("height", parseInt(baseHeight*1));
$(".win2", onePlane).css("height", parseInt(baseHeight*2));
$(".win3", onePlane).css("height", parseInt(baseHeight*3));
Each of these queries translates to: select all elements with .winX that are inside the jQuery object onePlane.
I would use all the same class names inside the nest and then just do $('.plane:eq(0) .win:eq(2)').html()
alert( $('.plane:eq(0) .win:eq(2)').html() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="plane">
<div class="win">Lorem ipsum</div>
<div class="win">Dolor sit</div>
<div class="win">amet.</div>
</div>
<div class="plane">
<div class="win">Lorem ipsum</div>
<div class="win">Dolor sit</div>
<div class="win">amet.</div>
</div>
if your classes are fixed then you can do with this code
$(".win1", $(".plane")).css("height", parseInt(baseHeight*1));
$(" .win2", $(".plane")).css("height", parseInt(baseHeight*2));
$(" .win3", $(".plane")).css("height", parseInt(baseHeight*3));
You can do using each loop of plane class.
$('.plane').each(function(){
baseHeight = 10;
$(this).find(".win1").css("height", parseInt(baseHeight*1));
$(this).find(".win2").css("height", parseInt(baseHeight*2));
$(this).find(".win3").css("height", parseInt(baseHeight*3));
});
Demo

Categories

Resources