getElementsByClassName('class') for ONLY the element that is clicked on - select

I have a series of divs with classes. I want to select the text within the div that is clicked on by the user.
In the example code below, if user clicks on the first div, the text consoled out should be: "Sample text ONE"
If the user clicks on the 2nd div, it should be "Sample text TWO"
I can accomplish what I want with divs that have Id's and getElementById('id').innerHTML
but I am forced to accomplish it with classes, which does not work.
Digging further:
I am understanding that getElementsByClassName returns an array like object, and document.getElementsByClassName(".sample_div")[0].innerHTML will kind of work, but it only returns the first element. Perhaps there is a way to replace the 0 with the index of the div that is clicked on?
Any way to do this with classes will be great. Thank you.
<!DOCTYPE html> <html>
<div class='sample_div'>Sample text ONE</div>
<div class='sample_div'>Sample text TWO</div>
</html>
<script type="text/javascript">
const divs = document.querySelectorAll('.sample_div');
divs.forEach(divSelect => divSelect.addEventListener('click', notice));
function notice() {
let text = document.getElementsByClassName('.sample_div').innerHTML;
console.log(text);
}

this will contain the clicked element
With jquery, you can create an event listener that listens to all .sample_div and reference it with this variable.
$(".sample_div").click(function(){
console.log(this.innerHTML)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='sample_div'>Sample text ONE</div>
<div class='sample_div'>Sample text TWO</div>
Without JQuery it should be like this:
//Get all the elements with the class "sample_div"
var sampleDivs = document.getElementsByClassName("sample_div")
//Iterate over the sampleDivs node array
for(var x=0, sampleDivsLength = sampleDivs.length; x<sampleDivsLength;x++){
//Add an event listener for each DOM element
sampleDivs[x].addEventListener("click",function(){
console.log(this.innerHTML)
})
}
<div class='sample_div'>Sample text ONE</div>
<div class='sample_div'>Sample text TWO</div>

Related

Jquery cannot find selector hidden by IziModal

IziModal is beautiful but Jquery selectors cannot see or find the modal elements it hides. So this code: var nextmodal = $(this).next('.izra'); $(nextmodal).iziModal('open'); , which can see any div hidden by display:none, can find any element EXCEPT divs hidden by Izimodal.
https://jsfiddle.net/zmbth7u9/4/ (Stack code snippet below)
Izimodal can find its own hidden div with class .izra but no Jquery selector can?
I've tried everything including div: $(this).next($(":hidden:first"));
console.log($(hiddenstuff))
The above code SKIPS OVER the Izimodal hidden div and finds the second!
I need to activate modals with generic classes repeated throughout documents for footnotes, saving code, markup and time.
Any idea how I can get Jquery selectors to find the div with the .izra class so I can act on it?
Since we cannot find siblings because IziModal hides them beyond reach, perhaps modal divs should begin without the .izra class (set to display:none by css) and dynamically add the .izra modal class upon hitting the click trigger? We could find the divs first with next(), then add the izra class, or would that put us back at square one?
Thank you!
https://jsfiddle.net/zmbth7u9/4/ The modal and finding divs in this fiddle works, and shows the lines that inexplicably don't work.
//How things should Work generically
$('.generictrigger').click(function () {
var nextmodal = $(this).next('.genericmodal');
$(nextmodal).modal('show');
});
//IziModal Initialize and fire on open
$(function () {
$(".izra").iziModal();
$('.izra').iziModal('open'); // This works!
});
//Proof hidden divs easily found when NOT hidden by IziModal
$(".trigger2").click(function () {
var hiddenstuff = $(this).next($(":hidden:first")); // This works!
console.log($(hiddenstuff))
});
//Proof IziModal divs cannot be found by Jquery selectors
$(document).on('click', '.trigger', function (event) {
event.preventDefault();
// $('.izra').iziModal('open'); // THIS WORKS!
var nextmodal = $(this).next('.izra'); // Should work but does not
console.log($(nextmodal));
$(nextmodal).modal('open'); // Should work but does not <<<<<<
});
.hidden { display: none; }
.c1 { background-color:#33ccff; }
.c2 { background-color:#ffff99; }
.c3 { background-color:#80ff80; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/izimodal/1.5.1/css/iziModal.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/izimodal/1.5.1/js/iziModal.js"></script>
<!-- Finding divs hidden by IziModal Begin -->
<!-- How things should generically work calling Next() -->
<div class="containerdivforchildren">
<div class="c1 generictrigger">Click for Generic Modal FOUND by NEXT Selector </div>
<div class="genericmodal modal fade modal-body modal-content"><a title="Close"><i data-dismiss="modal" class="glyphicon glyphicon-remove icon-arrow-right pull-left"></i></a>Generic Bootstrap Modal</div>
</div>
<!-- This section proves any div can be found EXCEPT divs touched by IziModal -->
<div class="modaltriggercontainer">
<div class="trigger2 c3">Click to Log var hiddenstuff = $(this).next($(":hidden:first"));to console</div>
<div class="trigger c2">Click to Open Izra (will fail but logs results of $(this).next() to console</div>
<div class="izra">Unretrievable modal div when hidden by IziModal class</div>
<!--Above DIV IS SKIPPED AND CANNOT BE FOUND!-->
<div id="incognito" class="c1 oddlynamed hidden">hidden by style but found using $(this).next()</div>
</div>
<!-- Above div is the first div found by any selector looking for the .next()-->

Swipe.js callback function

I'm using swipejs (https://github.com/bradbirdsall/Swipe) and want to add a class to certain DOM elements if the slide being slided to has a data attribute.
In this case a slide may have the attribute of data-colour="orange". When sliding to that slide I want to addClass '.orange' to any DOM element that hasClass '.colour'
HTML:
<!-- Slide 1 -->
<div class="slide" data-colour="orange">
<h1 class="center">we know sport</h1>
</div>
<!-- Slide 2 -->
<div class="slide" data-colour="blue">
<h1 class="center">we really know football</h1>
</div>
jQuery:
$(document).ready(function(){
var elem = document.getElementById('mySwipe');
window.mySwipe = Swipe(elem, {
callback: function(){
colour.addClass($('.slide').data('colour'));
}
});
});
This performs the desired action, but will only apply the data attribute of the current slide when sliding to the next slide, whereas I would like to work out the data attribute of the next slide, and when sliding to it add that as a class to other DOM elements.
Any help would be greatly appreciated.
Swipe 2.0 adds attribute data-index, so you could write:
$('#mySwipe [data-index='+(mySwipe.getPos()+1)+']').data('colour')

Jquery mobile : popup removed from DOM

In my JQUerymobile pages, I have embedded popup div.
Here is an example of my pages content :
<html>
<head>...</head>
<body>
<div data-role="page" id="myPage" data-dom-cache="true" data-theme="a">
<div data-role="content" data-theme="a" >...</div>
<div data-role="footer" data-theme="a" data-id="footer-sante" data-position="fixed">...</div>
<div data-role="popup" id="popupOne" data-dom-cache="true" data-theme="b">
</div>
</div>
<div data-role="popup" id="popupTwo" data-dom-cache="true" data-theme="b">
...
</div>
</body>
</html>
I navigate from pages to anothers. Suddently, my embedded popups disappear from my DOM when I inspect my code.
As shown in my example, the popup location in the source code doesn't seem to change anything to the problem.
Since popups are removed from DOM, the code bellow does nothing (it actually worked before) :
$('#popupOne').trigger('create');
$('#popupOne').popup({ transition: "slidedown", position:"position-header" });
$('#popupOne').popup('open');
Is there a solution to keep my popups in my DOM ?
Is there a better location to embed popups in source code ?
Another way could be to load a popup from an external (cached) page but i never achieved to do that by javascript.
Any idea to solve the problem (or a workaround) ?
(Both) your HTML placements might be incorrect here. Remove the popupOne markup from the end of the page and paste it inside the div with data-role=content like this :
<div data-role="page" id="myPage" data-dom-cache="true" data-theme="a">
<div data-role="content" data-theme="a" >
<div data-role="popup" id="popupOne" data-dom-cache="true" data-theme="b"></div>
</div>
<div data-role="footer" data-theme="a" data-id="footer-sante" data-position="fixed">...</div>
</div>
And if you want to reuse popups, I suggest you go the JS way. You could create popups n the fly and open them. Here's some code which does just that. Feel free to alter it to any thing you want :)
$.extend({
"makePopup": function (text) {
var $popup;
//creat popup element
$popup = $("<div/>", {
"data-role": "popup",
"data-theme": "a",
"data-overlay-theme": "a",
"data-transition": "pop"
}).popup();
//create close element
var $close = $("<a/>", {
"data-role": "button",
"html": "Close",
"href": "#",
"data-theme": "e"
}).on("click", function () {
//click event of close element
$(this).closest("[data-role=popup]").popup("close");
}).buttonMarkup();
//create content div - makes a nice jQM page structure.
var $content = $("<div/>", {
"data-role": "content",
//change this any way you want- Im just adding the text from clicked link here.
"html": "<span>" + text + "</span>"
});
//append $close to $content, then append $content to $popup
$content.append($close).appendTo($popup);
return $popup;
}
});
And when you want to use this, just do this,
var popupEl = $.makePopup("Some HTML");
And then you could, say, open it :
popupEl.popup("open");
Or simply,
$.makePopup("Some HTML").popup("open");
Here's a demo : http://jsfiddle.net/hungerpain/xjz3V/
Hope this is what you wanted :)

jQuery next() selector when divs are not neighboring

Ive been using the following to change the width of the div.my-div that appears after the one you've clicked:
$(".my-div").click(function () {
$(this).next().css({'width':'500px'});
});
As my divs were neighboring, this worked fine:
<div class="my-div">stuff</div>
<div class="my-div">stuff</div>
<div class="my-div">stuff</div>
However now the structure has changed so they are no longer neighboring:
<div>
<div class="my-div">stuff</div>
</div>
<div>
<div>
<div class="my-div">stuff</div>
</div>
</div>
<div class="my-div">stuff</div>
Whats the simplest way to select the next element of the same class?
Thanks
jQuery will return elements in order of their appearance in the DOM.
As such, you could cache all the .my-div elements, use the index()[docs] method to get the index of the one that received the event, increment it and use the eq()[docs] method to get the next one.
var divs = $(".my-div"); // cache all of them
divs.click(function () {
var idx = divs.index( this ); // get the index in the set of the current one
divs.eq( idx + 1 ).css({'width':'500px'}); // get the one at the next index
});
This saves you from doing a bunch of unnecessary DOM selection and traversing.
Example: http://jsfiddle.net/VrATm/1/
EDIT: Posted wrong example link. Fixed.
You can traverse the tree hierarchy. That is, you can first jump to parent, then to next, then to children, like this:
$(this).parent().next().find(' > div').css({'width':'500px'});

How to use "this" and not "this" selectors in jQuery

I have 4 divs with content like below:
<div class="prodNav-Info-Panel">content</div>
<div class="prodNav-Usage-Panel">content</div>
<div class="prodNav-Guarantee-Panel">content</div>
<div class="prodNav-FAQ-Panel">content</div>
And a navigation list like this:
<div id="nav">
<ul id="navigation">
<li><a class="prodNav-Info" ></a></li>
<li><a class="prodNav-Usage" ></a></li>
<li><a class="prodNav-Guarantee"></a></li>
<li><a class="prodNav-FAQ" ></a></li>
</ul>
</div>
When the page is first displayed I show all the content by executing this:
$('div.prodNav-Usage-Panel').fadeIn('slow');
$('div.prodNav-Guarantee-Panel').fadeIn('slow');
$('div.prodNav-FAQ-Panel').fadeIn('slow');
$('div.prodNav-Info-Panel').fadeIn('slow');
Now, when you click the navigation list item it reveals the clicked content and hides the others, like this:
$('.prodNav-Info').click( function() {
$('div.prodNav-Info-Panel').fadeIn('slow');
$('div.prodNav-Usage-Panel').fadeOut('slow');
$('div.prodNav-Guarantee-Panel').fadeOut('slow');
$('div.prodNav-FAQ-Panel').fadeOut('slow');
});
So what I have is 4 separate functions because I do not know which content is currently displayed. I know this is inefficient and can be done with a couple of lines of code. It seems like there is a way of saying: when this is clicked, hide the rest.
Can I do this with something like $(this) and $(not this)?
Thanks,
Erik
In your particular case you maybe able to use the .sibilings() method something like this:
$(this).fadeIn().sibilings().fadeOut()
Otherwise, lets say that you have a set of elements stored somewhere that points to all of your elements:
// contains 5 elements:
var $hiders = $(".prodNavPanel");
// somewhere later:
$hiders.not("#someElement").fadeOut();
$("#someElement").fadeIn();
Also, I would suggest changing the classes for your <div> and <a> to something more like:
<div class="prodNavPanel" id="panel-Info">content</div>
....
<a class="prodNavLink" href="#panel-Info">info</a>
This gives you a few advantages over your HTML. First: the links will have useful hrefs. Second: You can easily select all your <div>/<a> tags. Then you can do this with jQuery:
$(function() {
var $panels = $(".prodNavPanel");
$(".prodNavLink").click(function() {
var m = this.href.match(/(#panel.*)$/);
if (m) {
var panelId = m[1];
$panels.not(panelId).fadeOut();
$(panelId).fadeIn();
return false; // prevents browser from "moving" the page
}
});
});