I'm trying to learn jquery and I'm having some difficulty figuring out how to deal with a set of jquery results. Let's say I have some html like:
<div class="divClass">
<p class="pClass1">1</p>
<p class="pClass2">Some text.</p>
</div>
<div class="divClass">
<p class="pClass1">2</p>
<p class="pClass2">Some text.</p>
</div>
<div class="divClass">
<p class="pClass1">3</p>
<p class="pClass2">Some text.</p>
</div>
I want to loop through the div's with a class of "divClass", get the value contained in the child p with a class of "pClass1". Getting the set of div's with a class of "divClass" is easy with something like:
divs = $(".divClass");
But I'm not sure how to loop through "divs" and find the "pClass1" child, then get its value. Any help would be much appriciated.
You can use the each method, and then, look for the '.pClass' elements, in the context of this, which is the currently div being iterated:
var divs = $(".divClass");
divs.each(function () {
alert($('p.pClass1', this).text());
});
Check the above example here.
Use the each method:
$(".divClass").each(function() {
});
There are lots of ways.
For your specific scenario, I would try something like this:
$(".divClass .pClass1").each(function() {
// Do whatever
});
If you wanted to do something with the div tags and the p tags, you could try the find method:
$(".divClass").each(function() {
var p1Tags = $(this).find(".pClass1");
});
Related
I was wonder how I can toggle one element without toggling others... I just don't want to do this every time:
HTML:
<div class="share-toggle as-1"></div>
<div class="audio-share as1">
<p>Some Text</p>
</div>
<div class="share-toggle as-2"></div>
<div class="audio-share as2">
<p>Some Text</p>
</div>
JS:
$('.as-1').click(function() {
$('.as1').slideToggle('fast');
});
$('.as-2').click(function() {
$('.as2').slideToggle('fast');
});
Is there a way to write this in short? pls help... thx
You can use jQuery to select all elements, which className contains a certain substring:
$('*[class*="as-"]')
This will select all Elements in the DOM (*), of which the className ([class=""]) has "as-" anywhere (*) in it.
And then you can use the Element passed as this to get the number of the element after the "as-" and toggle the wanted element:
$('*[class*="as-"]').click(function () {
let elemNum = this.className.match(/as-(\d+)/)[1];
$("as"+elemNum).slideToggle('fast');
});
I know you already accepted an answer, but anyway…
Here is, in my opinion, a better solution.
Why is that?
Only 3 lines of code, and not using any regex or partial class names…
See comments in my code for more details:
// You could use class^=[as-] to filter on the classes that start with as-,
// (the ^ would be better than a *, because more specific)
// But I suggest you to use the 'share-toggle' class, there's no need to complicate things here:
$('.share-toggle').on('click', function(){
// The following will get the .audio-share element that is after the element we just clicked,
// If your HTML structure is gonna stay well structured like this, it's the finest solution:
$(this).next('.audio-share').slideToggle('fast');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="share-toggle as-1">[ CLICK HERE ]</div>
<div class="audio-share as1">
<p>Some Text</p>
</div>
<div class="share-toggle as-2">[ CLICK HERE ]</div>
<div class="audio-share as2">
<p>Some Text</p>
</div>
I hope you will consider this answer.
And I hope it will help!
I have this situation:
<div id="first">
<div>
<p>text</p>
</div>
</div>
<div id="second">
<div>
<button class="button">click</button>
</div>
</div>
...
<div id="first"> ... </div>
<div id="second"> ... </div>
...
and so on, the structure repeats.
This structure is created dynamically so I can't use any specific class nor id for the first div.
I need to retrieve the text in the first div when I hit the button in the second div.
(NOTE: I need a pure javascript solution, not a jQuery solution)
Thanks
Assuming you have an event handler for the button click, you could do this from that event handler:
function buttonClickHandler(e) {
var first = this.parentNode.parentNode.previousSibling;
var paragraphs = first.getElementsByTagName("p");
var text = paragraphs[0].textContent;
}
If you have common and known class names on the the divs marked first and second, then you can make your Javascript code much more insulated from markup changes which is generally a good idea.
P.S. I presume you know that you should't have duplicate id values in your HTML. This code doesn't use them, but you should be using class names instead of id values if you're going to have duplicates.
I am using this div code
<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>
and trying to print the values like
japp.init = function () {
console.log($("div").data("role"));
console.log($("div").data("lastValue"));
console.log($("div").data("hidden"));
console.log($("div").data("options").name);
});
This works fine if I put the above div tag directly inside body but as I put the div tag inside any other div tag it does not work and says undefined.
<div class="page">
<div data-role="page" data-last-value="43" data-hidden="true" data- options='{"name":"John"}'></div>
</div>
console prints undefined for above html.
Please let me know if anything is not clear
When getting data jQuery returns data from the first element matching selector, if the first div in DOM has no data - jquery won't return it.
try
japp.init = function () {
console.log($("div[data-role]").data("role"));
console.log($("div[data-lastValue]").data("lastValue"));
console.log($("div[data-hidden]").data("hidden"));
console.log($("div[data-options]").data("options").name);
});
or better give this div an id, and select by id like $('#someid').data('role')
Your selector is div and when you have more divs on your page jQuery will select (in this case) the first one.
<div class="page">
<div data-role="page" data-last-value="43" data-hidden="true" data- options='{"name":"John"}'></div>
</div>
In the above HTML the first div does not have data-* so it will result with an undefined value
You have to be more specific with your selectors
$('.page div').data('role')
Or
$('div:first div').data('role')
Try
$("div.page div").each(function(){
console.log($(this).data("whatever_you_need"));
});
etc.
This way you will cycle through all divs nested in div with class 'page'.
You aren't exactly specifying which div to get. Whenever you are trying to get specific data from a specific element, you should be sure which div you are accessing. This can either occur within an iteration of elements or by ID or an element in relation to an ID. It shouldn't be done based on tagname or even classname as they can be multiple. In this case, why not add an ID on the div you are trying to get so you can access it specifically:
<div class="page">
<div id="thisDiv" data-role="page" data-last-value="43" data-hidden="true" data- options='{"name":"John"}'></div>
</div>
Then access:
console.log($("#thisDiv").data("role"));
Also, it is bad for performance to wrap the same jquery object over and over, you can cache it like this:
$thisDiv = $("#thisDiv");
console.log($thisDiv.data("role"));
....
I believe it is because $("div") returns all occurrences of div and then selects the first to perform a function on. I'm not sure how you want to use this functionality but it might be worth considering something like this
JSFiddle where a class is used to select the correct div
$(function(){
console.log($(".div").data("role"));
console.log($(".div").data("lastValue"));
console.log($(".div").data("hidden"));
console.log($(".div").data("options").name);
});
give your Div a class like class="myClass"
<div class="page">
<div class="myClass" data-role="page" data-last-value="43" data-hidden="true" data- options='{"name":"John"}'></div>
</div>
and then you can change your jquery selector:
japp.init = function () {
console.log($(".myClass").data("role"));
console.log($(".myClass").data("lastValue"));
console.log($(".myClass").data("hidden"));
console.log($(".myClass").data("options").name);
});
otherwise jquery don't know which div you are looking for.
I hope this will help
I am looking for a Javascript solution for this problem. I have the following HTML:
<div id = "container">
<div id = "data">
<div>
<h3> Address</h3>
<b>Expand...</b>
<div id="content">ul. Pomorska</div>
</div>
<div>
<h3> Telefon </h3> <b>Expand...</b>
<div id="content">26565352</div>
</div>
<div>
<h3>Email</h3>
<b>Expand...</b>
<div id="content">asdasdag#aga.com</div>
</div>
</div>
</div>
I would like to hide the content div when an onclick Expand is made. So far I have made a function which hides the content divs and tries to assign an event handler to the node.
function hideinfo() {
var node = document.getElementById("data");
var contactdata = node.getElementsByTagName("div");
for(var i=0; i<contactdata.length;i++) {
if(contactdata[i].id == "content") {
alert(contactdata[i].previousSibling.innerHTML);
contactdata[i].previousSibling.addEventListener('click',ShowHide,false);
contactdata[i].style.display="none";
}
}
}
The problem is that the alert displays undefined. Why can't it see the node? Is there a better way to do this in Javascript?
Because previousSibling is most likely the text node before the div element. You probably want to use previousElementSibling instead :)
In most browser today, querySelectorAll, which lets you use CSS selectors for finding elements, is also a good alternative (IE8+)
The previousSibling property returns the previous sibling node (the previous node in the same tree level) of the selected element
which returns in your case the TEXT node.
As you can see in this jsfiddle: http://jsfiddle.net/Xu383/
alert(contactdata[i].previousSibling.nodeName);
You are better of using the querySelectorAll.
Also you can't have multiple divs with the SAME id, use class instead.
I'm tinkering a bit with jquery to show a hidden div when a link is clicked. This should be fairly simple, but there's a flaw to it in this case. I have the following markup:
<div class="first-row">
<div class="week">
<p>Uge 2</p>
<p>(08-01-11)</p>
</div>
<div class="destination">
<p>Les Menuires</p>
<p>(Frankrig)</p>
</div>
<div class="days">4</div>
<div class="transport">Bil</div>
<div class="lift-card">3 dage</div>
<div class="accommodation">
<p><a class="show-info" href="#">Hotel Christelles (halvpension)</a></p>
<p>4-pers. værelse m. bad/toilet</p>
</div>
<div class="order">
<p>2149,-</p>
<p class="old-price">2249,-</p>
</div>
<div class="hotel-info">
<!-- The div I want to display on click -->
</div>
</div>
When I click the "show-info" link I want the "hotel-info" div to display.
My backend devs don't want me to use ids (don't ask me why..) and the above markup is used over and over again to display data. Therefore I need to be able to access the "hotel-info" div in the "first-row" div where the link is clicked.
I've tried to do something like:
$(document).ready(function() {
$('.show-info').click(function() {
var parentElement = $(this).parent().parent();
var lastElementOfParent = parentElement.find(".show-hotel");
lastElementOfParent.show();
});
});
But without a result :-/ Is this possible at all?
Any help is greatly appreciated!
Thanks a lot in advance!
Try this:
$('.show-info').click(function() {
$(this).closest('.accommodation').siblings('.hotel-info').show();
});
Even better imo, as it would be independent from where the link is in a row, if every "row div" has the same class (I assume only the first one has class first-row), you can do:
$(this).closest('.row-class').find('.hotel-info').show();
Reference: .closest, .siblings
Explanation why your code does not work:
$(this).parent().parent();
gives you the div with class .accommodation and this one has no descendant with class .hotel-info.
It is not a good idea to use this kind of traversal for more than one level anyway. If the structure is changed a bit, your code will break. Always try to use methods that won't break on structure changes.
You're right in not using an ID element to find the DIV you want :)
Use closest and nextAll
Live demo here : http://jsfiddle.net/jomanlk/xTWzn/
$('.show-info').click(function(){
$(this).closest('.accommodation').nextAll('.hotel-info').toggle();
});