How to get previous element from click target? - javascript

Hello I have this html code:
<div class="row newrow">
<div class="col-10"><b>this</b></div>
<div class="col-2">
<img src="close.png" id="exit"/>
</div>
</div>
When I click on img with id exit using this code
$('body').on('click','#exit',function(e){
})
I need to get the text of the <b>behind it which would be "this"
I have tried this but it does not work:
$('body').on('click','#exit',function(e){
$q = $(e.target).prev('b')
var word = $q.text()
)}
It only gives me the that I clicked from the beginning

try this:
$('body').on('click','#exit',function(e){
var this_b = $(this).parent().prev().children(0).html();// get the text
alert(this_b);
});

You can use $(this).closest('.row').find('b'):
$('#exit').click(function(e){
$q = $(this).closest('.row').find('b');
var word = $q.text();
console.log(word);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row newrow">
<div class="col-10"><b>this</b></div>
<div class="col-2">
<img src="close.png" id="exit"/>
</div>
</div>

You need to select the parent of the clicked img to get the the .col-2, and then get the col-2's prev() to get to the .col-10, and then you can access its children() to get the children (the single <b>). Also, there's no need for e.target if you use this:
$('body').on('click', '#exit', function() {
$q = $(this).parent().prev().children();
var word = $q.text()
console.log(word);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row newrow">
<div class="col-10"><b>this</b></div>
<div class="col-2">
<img src="close.png" id="exit" />
</div>
</div>

Try this
$('body').on('click','#exit',function(e){
var word = $(this).closest('.newrow').find('b').text();
});

Related

Find the index of a div inside a container

I have a container with multiple divs and in each div I have a handler on which you can click.
The requirement is to return the index of the div in the container for further processing.
I've simplified the code for readability purposes.
The HTML:
<div class="container">
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
</div>
The Javascript code I tried so far but I always get -1 as the index:
$(document).ready(function(){
$('.handler').click(function(e) {
let index = Array.prototype.indexOf.call($('.container'), $(this).parents('.block'));
console.log(index);
});
});
I also created a fiddle.
So what am I doing wrong here?
You can do the following,
$('.handler').click(function(e) {
var el = e.target;
console.log([].indexOf.call(el.parentNode.parentNode.children, el.parentNode));
});
However if you want to know what was wrong in your code,
Array.prototype.indexOf.call($('.container')[0].children, $(this).parents('.block')[0])
This part should fix the problem in your code. You have been doing it all right, but for the parameter of indexOf we needed the children array of .container and clicked element.
You were passing the container element and current clicked element as an array. That is Array.prototype.indexOf.call('[Container Element]', ['current clicked div']) Which is not right. You should pass something like this,
Array.prototype.indexOf.call('[children, children, children...]', 'current clicked div element').
It was happening because the $('.container') returns an array with the element having a class name .container. But we needed all the children array of the element that contains container class.
And $(this).parents('.block') returns an array with the matching elements even if it is only one.
You can access the index using the index method on parent element of selection.
$(document).ready(function(){
$('.handler').click(function(e) {
console.log($(this).parent().index())
});
});
You can do that like this. Find the index of the closest element of the clicked element, which is also a direct child of .handler. To find index, use index().
$(document).ready(function() {
$('.handler').click(function(e) {
let index = $(this).closest('.block').index()
console.log(index);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
</div>
You're checking at the wrong level of nesting in your HTML. I believe what you're trying to do is check from one level higher, at ".container" and get the index of the ".block" element that was clicked.
This code works in your Fiddle:
$(document).ready(function(){
$('.handler').click(function(e) {
const p = e.target.parentElement.parentElement;
const index = Array.prototype.indexOf.call(p.children, e.target.parentElement);
console.log(p.className) // "container"
console.log(index)
});
});
This can be done simply using delegate in jQuery.
I modify your JSFiddle code.
$(".container").delegate('.block', 'click', function () {
console.log( $(this).index() );
})
u can use a id
<div class="container">
<div class="block">
<div id='0' class="handler">
Click
</div>
</div>
<div class="block">
<div id='1' class="handler">
Click
</div>
</div>
<div class="block">
<div id='2' class="handler">
Click
</div>
</div>
<div class="block">
<div id='3' class="handler">
Click
</div>
</div>
</div>
$(document).ready(function(){
$('.handler').click(function(e) {
let index = this.id
console.log(index);
});
});
https://jsfiddle.net/vhrt596x/2/

How to check if inner <div> has text

what I'm trying to do is to check if my inner <div> has a text for example Ended and then remove if it has a text. I have multiple <div> with the same class name. I tried using .filter(). I would like to remove the div container_one that contains the found element.
Here is my HTML:
var $filstatus = $('.status').filter(function() {
return $(this).text() == 'Ended';
});
$filstatus.remove();
<div class="main_container">
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">On going</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
</div>
Thank you for the help!
I would use the jQuery's selector by content
combined with .closest(). This might be the shortest way:
$('.status:contains("Ended")', $('.main_container')).closest('.container_one').remove();
First ('.status:contains("Ended")') will select all elements that have a class status, contain the text "Ended" and are children of main_container (not needed but is recommended to speed up selection of elements on complex pages).
Then the method .closest('container_one') will climb up the parents tree for each of the elements from the previous step and select the first parent element with class 'container_one'.
At last it will remove all elements found.
Note: all those methods work both with single element and collections of elements, so no need of any for/foreach.
Working JSFiddle Demo
Pure JavaScript solution with forEach:
var div = document.querySelectorAll('.container_one');
div.forEach(function(el){
var target = el.querySelector('.status');
if(target.textContent == 'Ended'){
el.remove();
};
})
<div class="main_container">
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">On going</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
</div>
Try this
$filstatus.parent().parent().remove();
filter will return an array , then use each to loop over that and delete the element. In this case it will remove that specific div but the parent div will still be in dom
var $filstatus = $('.status').filter(function() {
return $(this).text().trim() === 'Ended';
});
$filstatus.each(function(index, elem) {
$(elem).remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main_container">
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">On going</div>
</div>
</div>
<div class="container_one">
<div class="inner_container">
<div class="status">Ended</div>
</div>
</div>
</div>
If you want to remove .container_one whose inner child has the text Ended, try
const ended = $('.status').filter((index, element) => $(element).text() === 'Ended')
ended.parents('.container_one').remove()
Since you want to remove the closest ansistor with class .container_one, you will need to use closest
$filstatus.closest(".container_one").remove();
Check this: https://jsfiddle.net/n3d5fwqj/1/
https://api.jquery.com/closest/
Try using this if you don't need $filstatus in other places
$('.status').each(function(){
if ($(this).text() == "Ended"){
$(this).parent().parent().remove();
}
})
I see your problem is you are able to remove the child div status but what you want is to remove the entire parent div with class container_one
you can use $.each for that and use closest(class_name) to remove the parent including its child
$.each($('.status'), function(idx, div) {
if ($(this).text() == 'Ended') {
$(this).closest('.container_one').remove();
}
});
Demo
or you can continue your filter and just add .closest('.container_one') to your jquery selector
var $filstatus = $('.status').filter(function() {
return $(this).text() == 'Ended';
});
$filstatus.closest('.container_one').remove();
Demo

How to get the value in element child when click a div outside element parent JQuery

Sorry my english bad, for example I have 2 columns, every column when click div.open-model will show a model have a value is h3.title, I used jQuery but i cannot get value h3.title every column
$(document).ready(function() {
$('.open_modal').click(function(e) {
var h3title = $(this).find('.parent .title').html();
console.log('h3title');
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<h3 class="title">Title1</h3>
</div>
<div class="open-model">Open model</div>
<div class="parent">
<h3 class="title">Title2</h3>
</div>
<div class="open-model">Open model</div>
Try prev().
var h3title = $(this).prev('.parent').find(".title").text();
And after fixing other errors
$(document).ready(function() {
$('.open-model').click(function(e) {
var h3title = $(this).prev('.parent').find(".title").text();
console.log(h3title);
e.preventDefault();
});
});
You've got several issues here:
The class on the element is open-model so your selector of open_modal is incorrect
find() looks for child elements, yet the target you want to find is a child of a sibling, so you need prev().find() instead
h3title is a variable, so you don't need to wrap it in quotes when passing it as an argument to console.log().
Try this:
$(document).ready(function() {
$('.open-model').click(function(e) {
e.preventDefault();
var h3title = $(this).prev('.parent').find('.title').text();
console.log(h3title);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<h3 class="title">Title1</h3>
</div>
<div class="open-model">Open model</div>
<div class="parent">
<h3 class="title">Title2</h3>
</div>
<div class="open-model">Open model</div>
spelling of selector is wrong on click
use .prev() instead of .find()
$('.open-model').click(function(e) {// fix selector
var h3title = $(this).prev('.parent').find('.title').html();//use prev()
console.log(h3title);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<h3 class="title">Title1</h3>
</div>
<div class="open-model">Open model</div>
<div class="parent">
<h3 class="title">Title2</h3>
</div>
<div class="open-model">Open model</div>
Change it to
$(document).ready(function(){
$('.open-modal').click(function(e){
e.preventDefault();
var h3title = $(this).prev().find('.title').text();
console.log('h3title');
});
});
In the example below we are getting the the previous DOM element and as we can see in the structure we want to get the inner text of its child element.
$('.open-model').on('click', function(){
console.log($(this).prev().children().text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<h3 class="title">Title1</h3>
</div>
<div class="open-model">Open model</div>
<div class="parent">
<h3 class="title">Title2</h3>
</div>
<div class="open-model">Open model</div>

Toggle multiple classes

I'm stuck with a menu I'd love to add to my website.
I have branched my work in:
Commercial
Fashion
Music
Portrait
So I have a menu like this one above.
When I click on one section, let's say "Commercial" I want all the others to be display:none.
Have a look at this FIDDLE: http://jsfiddle.net/bfevLsj2/8/
$(document).ready(function() {
$("#commercial").click(function() {
$(".commercial").toggleClass("show");
$(".fashion").toggleClass("hid");
$(".music").toggleClass("hid");
$(".portrait").toggleClass("hid");
});
});
You need siblings() width jquery
Description: Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
$("[id]").click(function(){ //onclick on element with ID
var selected = $(this).attr("id"); // save the value of that ID
$("."+ selected).show().siblings("[class]").hide()//find the class with the same value as class and show it then find all siblings class and hide them
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="commercial">Commercial</div>
<div id="fashion">Fashion</div>
<div id="music">Music</div>
<div id="portrait">Portrait</div><br />
<div class="commercial">C</div>
<div class="fashion">F</div>
<div class="music">M</div>
<div class="portrait">P</div>
BUT a better approach would be to use data-*
$("[data-tab]").click(function(){
var current = $(this).attr("data-tab");
$("[data-content="+ current +"]").show().siblings("[data-content]").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div data-tab="commercial">Commercial</div>
<div data-tab="fashion">Fashion</div>
<div data-tab="music">Music</div>
<div data-tab="portrait">Portrait</div><br />
<div data-content="commercial">C</div>
<div data-content="fashion">F</div>
<div data-content="music">M</div>
<div data-content="portrait">P</div>
AGAIN it is better to use pure javascript
function runClick (event) {
var current = this.getAttribute("data-tab");
for( var content = 0; content < dataContent.length; content++) {
dataContent[content].style.display = "none"
}
document.querySelector("[data-content="+ current + "]").style.display = "block"
}
var dataTabs = document.querySelectorAll("div[data-tab]"),
dataContent = document.querySelectorAll("div[data-content]");
for(var tab = 0; tab < dataTabs.length; tab++){
dataTabs[tab].addEventListener("click", runClick , false);
}
<div data-tab="commercial">Commercial</div>
<div data-tab="fashion">Fashion</div>
<div data-tab="music">Music</div>
<div data-tab="portrait">Portrait</div><br />
<div data-content="commercial">C</div>
<div data-content="fashion">F</div>
<div data-content="music">M</div>
<div data-content="portrait">P</div>
HTML:
<div id="commercial" class="menuItem">Commercial</div>
<div id="fashion" class="menuItem">Fashion</div>
<div id="music" class="menuItem">Music</div>
<div id="portrait" class="menuItem">Portrait</div><br />
<div class="commercial content">C</div>
<div class="fashion content">F</div>
<div class="music content">M</div>
<div class="portrait content">P</div>
JavaScript:
$(document).ready(function(){
$(".menuItem").click(function(){
var id = this.id;
$('.content').removeClass('show').addClass('hid');
$('.'+id).addClass('show').removeClass('hid');
});
});
CSS:
.hid {
display:none;
}
.show {
display:block;
}
Fiddle
Have a look at this fiddle, think it's what you want
Essentially you can use .toggle() to traverse and show/hide according to whether it's the one you want to show.
$(function(){
// find all the links that you can click
$("div.clickable a").click(function(e) {
// when they're clicked, find the identifier of
// the tab/div you want shown
var clickedId = $(e.target).parent("div").attr("id");
// traverse all of the divs and show/hide according
// to whether it's the tab you want
$("div.section").each(function(index, div) {
$(div).toggle($(div).hasClass(clickedId));
});
});
});
And the HTML:
<div id="commercial" class="clickable">Commercial</div>
<div id="fashion" class="clickable">Fashion</div>
<div id="music" class="clickable">Music</div>
<div id="portrait" class="clickable">Portrait</div>
<br />
<div class="commercial section">C</div>
<div class="fashion section">F</div>
<div class="music section">M</div>
<div class="portrait section">P</div>
HTH
Edited to add an "ALL" link in this fiddle
$("div.clickable a").click(function(e) {
// when they're clicked, find the identifier of
// the tab/div you want shown
var clickedId = $(e.target).parent("div").attr("id");
// traverse all of the divs and show/hide according
// to whether it's the tab you want
$("div.section").each(function(index, div) {
$(div).toggle($(div).hasClass(clickedId) || clickedId=="ALL");
});
});
After adding this to the list of clickable divs:
<div id="ALL" class="clickable">
ALL
</div>
Your could that more easy like:
<div class="link" id="commercial">Commercial</div>
<div class="link" id="fashion">Fashion</div>
<div class="link" id="music">Music</div>
<div class="link" id="portrait">Portrait</div><br />
<div class="commercial elem">C</div>
<div class="fashion elem">F</div>
<div class="music elem">M</div>
<div class="portrait elem">P</div>
<script type="text/javascript">
$(document).ready(function(){
$(".link").click(function(){
var id = $(this).attr('id');
$('.elem').hide();
$('.' + id).show();
});
});
</script>

How to alter the value of a div on each click

I have got a task to create a puzzle.I have 12 div.Each div contains different value up to 12.I have button like start now.I want to change my div value on each click of the start now button.
DEMO
<div id="container">
<div class="finder">
<div class="block1"> <div id="one"><h1>1</h1></div>
</div>
<div class="block1"> <div id="two"><h1>2</h1></div>
</div>
<div class="block1"> <div id="three"><h1>3</h1></div>
</div>
<div class="block1"> <div id="four"><h1>4</h1></div>
</div>
<div class="block1"> <div id="five"><h1>5</h1></div>
</div>
<div class="block1"> <div id="six"><h1>6</h1></div>
</div>
<div class="block1"> <div id="seven"><h1>7</h1></div>
</div>
<div class="block1"> <div id="eight"><h1>8</h1></div>
</div>
<div class="block1"> <div id="nine"><h1>9</h1></div>
</div>
<div class="block1"> <div id="ten"><h1>10</h1></div>
</div>
<div class="block1"> <div id="eleven"><h1>11</h1></div>
</div>
<div class="block1"> <div id="twelve"><h1>12</h1></div>
</div>
</div>
<div class="button">
<div id="startButton">
<button>Start</button>
</div>
</div>
</div>
js is
$(".finder").css('display','none');
$("#startButton").click(function () {
$(".finder").css('display','block');
});
var myDiv;
$(".block1 div").on('click', function(){myDiv = $(this)});
$(".block1 div").click(function () {
if(myDiv.text() < 12)
{
myDiv.text(parseInt(myDiv.text())+1);
}
if(myDiv.text() > 12)
{
myDiv.text(1);
myDiv.text(parseInt(myDiv.text())+1);
}
});
How can i change the values?
I have provided a solution below. One of the key takeaways you should get from it, is that when an event handler is used this will be assigned the element the event was trigger on within the bound function.
To Fill the boxes with random numbers use this code
$(function() {
//Array of values
var values = [1,2,3,4,5,6,7,8,9,10,11,12];
$( "input[type=submit], button" )
.button()
.click(function( event ) {
event.preventDefault();
});
$(".finder").css('display','none');
$("#startButton").click(function () {
var tmpValues = values.slice(); //copy array
$(".block1 div h1").each(function(){
var r = Math.floor(Math.random()*tmpValues.length);
//assign html to random array value that gets removed from array
$(this).html(tmpValues.splice(r,1));
});
$(".finder").css('display','block');
});
$(".block1 div").click(function () {
//Instead of setting myDiv use $(this) which will refer to the div
//We can grab the value of the H1 within the div using a scoped selector
var value = parseInt($("h1",this).html());
//Set the html of the clicked div
//When setting the html we must include new value in h1 to maintain style
//Ternary expression tidies up the logic, not sure why it sets to to 2 though?
$(this).html("<h1>" + ((value > 12) ? 2: value+1) + "</h1>");
});
});
Working Example http://jsfiddle.net/W55xc/3/
I didnt quite get the question, but I guess you want to generate random numbers for the div's, right? Use Math.random()
$(".block1 div").each(function() {
$(this).children('h1').text(Math.floor((Math.random() * 12) + 1)); // Generate a random number <-> [1, 12]
}

Categories

Resources