A website on Chrome has the following structure:
<div class="divClass">
<a class="aClass"></a>
<a class="aClass"></a>
<a class="aClass"></a>
</div>
I'm using JQuery to get all the "a" elements inside the div. They all have the same class. The code I'm using in the devTools is this:
$("div[class='divClass'] > a")
But it only returns the first "a" element. How can I get all of them?
Snippet:
console.log($("div[class='divClass'] > a"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divClass">
<a class="aClass"></a>
<a class="aClass"></a>
<a class="aClass"></a>
</div>
You can just use $('.divClass > a')
An alternative is to use find() which gets the descendants of each element in the current set of matched elements so it can be helpful here
$(".divClass").find("a")
More about find - https://api.jquery.com/find/
use .children method,
/*
var a1 = $(".divClass").children("a")[0].text;
var a2 = $(".divClass").children("a")[1].text;
var a3 = $(".divClass").children("a")[2].text;
*/
var aaa = $(".divClass").children("a").text();
console.log(aaa);
You can use a different selector, for instance:
$(".divClass > a.aClass")
This will find all a tags with class aClass that are immediate children of an element with class divClass. If you want to find all children throughout the DOM tree (i.e. grandchildren, great grandchildren, etc) then you can use omit the > operator.
You can then act on all elements matching these criteria (for instance .addClass("found"), or cycle through them individually using .each( function() { ....}) if you need to pull element specific information from them.
The demo below is fully commented.
DEMO
// Add click event to test button
$("#test").click( function() {
// ACT ON ALL IN ONE LINE
// Use jquery to find all direct children of elements with class divClass that are 'a' tags with class 'aClass'
// Add red border using CSS styles
$(".divClass > a.aClass").addClass("directChildren");
// Find grandchildren, great grandchildren, etc
// Turn color of text blue using CSS
$(".divClass a.aClass").addClass("allChildren");
// HOW TO CYCLE TRHOUGH EACH LINK
// Cycle through each, find them using same technique as above
$(".divClass > a.aClass").each( function() {
// Prove we've found each individual link
console.log($(this).text());
});
});
.directChildren {
border: red 2px solid;
}
.allChildren {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divClass">
<a class="aClass">Link 1</a>
<a class="aClass">Link 2</a>
<a class="aClass">Link 3</a>
<div style="padding:12px;">
<a class="aClass">Grandchild Link 1</a>
</div>
</div>
<button id="test">Find Children</button>
Related
I want to know how to access a specific element in a div when foreach-ing
Here is some code
HTML
<div class="row menu-filter-items">
<div class="col-md-4 margin-b-30 menu-item">
<a href="#" class="menu-grid">
<img src="images/img-1.jpg" alt="" class="img-fluid"/>
<div class="menu-grid-desc">
<!-- <span class="price float-right">$9.50</span> -->
<h4 class="a" id="title">Restaurant y</h4>
<p>
Description
</p>
</div>
</a>
</div>
</div>
Jquery:
$('#search').keyup(function(e){
var current_query = $('#search').val();
if(current_query != null)
{
$("div.menu-filter-items").hide();
$("div.menu-filter-items div.menu-item").each(function(){
var current_keyword = $(this).children('#title').text();
alert(current_keyword);
if (current_keyword.indexOf(current_query) >=0)
{
$("div.menu-filter-items").show();
}
});
}
else
{
$("div.menu-filter-items").show();
}
});
I want to access the H4 balise but I couldn't
Help please
thank you
Use
var current_keyword = $(this).find('#title').text();
instead of
var current_keyword = $(this).children('#title').text();
You should use find method.
The .children() method allows us to search through the children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements as well.
You can use find to perform a search with Jquery lib.
See full doc here : https://api.jquery.com/find/
For your case; you can use :
$( "div.menu-filter-items" ).find( "h4" )
I'm trying to link one div with the href attribute of his first <a> href.
My html looks like this
<div class="clicked">
<a class="i-want-this-href" href="target">
<img>
</a>
<a class="this-one-is-useless" href="Wrong-target">
<img>
</a>
</div>
And I have tested some different ways like this:
$('.clicked').on('click',function(){
aux= $('this:first-child').attr("href");
console.log(aux);
});
But I always get Undefined on the console. And I want to get "target" inside the first <a> element.
Any help will be appreciated!
Your selector is incorrect, you can use .find()/.children() along with :first selector
aux= $(this).find('a:first').attr("href");
Use this context along with :first-child selector
$('.clicked').on('click', function() {
var href = $(this).find('a:first-child').attr("href");
console.log(href);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="clicked">
<a class="i-want-this-href" href="target">
<img>
</a>
<a class="this-one-is-useless" href="Wrong-target">
<img>
</a>
1) Do not use this in selectors, this needs to be passed to $ separately
2) Make sure to declare variable as local, otherwise there will be bugs.
3) Use first-of-type
$('.clicked').on('click',function(){
var aux = $(this).find('a:first-of-type').attr("href");
console.log(aux);
});
$('.clicked').on('click',function(){
aux= $(this).find('a:first-child').attr("href");
console.log(aux);
});
Wrong selector, If you want to use this in selector you should pass it separared as follows :
var aux = $('a', this).prop("href");
//Or
var aux = $(this).find('a').prop("href");
NOTE : jQuery by default will select the first occurrence.
Hope this helps.
$('.clicked').on('click',function(){
var aux = $('a', this).prop("href");
console.log(aux);
});
.clicked{
width:100%;
height:100px;
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clicked">
<a class="i-want-this-href" href="target">
Image 1
</a>
<a class="this-one-is-useless" href="Wrong-target">
Image 2
</a>
</div>
I would like to add a class to the outer (parent) container based on the content of a child container. I am able to add a class to the child container based on its content, but If I try to add the class to the parent container, it does it to all of the containers on the page instead of just the current container. Could someone help me update my code so that it only adds the class to the parent container and not all containers that share the same class? Thanks.
jQuery:
$('div.promotion-type').each(function () {
var promotion = $(this).html();
console.log(promotion);
if (promotion === "Special Event") {
$("div.calendar-event").addClass("special-event"); // this is the only one with a class created for it so far
} else if (promotion === "Daily Promotion") {
$("div.calendar-event").addClass("daily-promotion");
}
});
HTML: (1 of many containers)
<li class="hidden-xs col-sm-6 col-md-4">
<div class="calendar-event">
<div class="event-details-container">
<div class=" col-xs-4 calendar-thumbnail">
<a href="/warroad-calendar/canadian-day">
<img src="/_images/warroad/calendar/may-june-2014/canadianDay.jpg" border="0" alt="" />
</a>
</div>
<h3>Canadian Day</h3>
<h4>8 a.m. - 6 p.m.</h4>
<strong></strong><br />
<div class="hidden-xs hidden-sm hidden-md hidden-lg promotion-type">Daily Promotion</div>
</div>
</div>
</li>
Change this:
$("div.calendar-event").addClass("special-event");
to this:
$(this).parents("div.calendar-event").addClass("special-event");
As it appears you already know, using the selector $("div.calendar-event") is going to select all <div> elements with the class calendar-event.
By using $(this).parents("div.calendar-event"), you're going to look through all parents of the starting <li> element, starting with the closest parent and progressing outwards. When it finds the parent that is a <div> element with the class calendar-event, it's going to call .addClass() on that parent element.
The problem is that you are doing a new selection instead of using the current element. Try...
$(this).parent().parent().addClass(...);
...or possibly...
$(this).parents('div.calendar-event').addClass(...);
...instead.
Instead of this-
$("div.calendar-event", this).addClass("special-event");
try this:
this.find("div.calendar-event").addClass("special-event");
Use text() instead of html()
remove the classes first
use $(this)
Code:
$('div.promotion-type').each(function () {
var promotion = $(this).text();
console.log(promotion);
$(this).parent().removeClass("special-event");
$(this).parent().removeClass("daily-promotion");
$(this).parent().addClass(
promotion === "Special Event" ? 'special-event': 'daily-promotion');
});
jQuery
$(".drop-down h3").click(function(e) {
e.preventDefault();
$(this).parent(".drop-down").find($("ul")).stop().slideToggle();
$(this).parent(".drop-down").find($(".divider-aside")).stop().toggle("slow");
$(this).parent(".drop-down").find($(".arrow")).stop().toggleClass("rotate1 rotate2");
});
HTML
<div id="categories">
<div class="drop-down">
<h3>Categories</h3>
</div>
<div class="divider-aside"></div>
<ul>
<li>123</li>
<li>12323</li>
<li>1231</li>
<li>523</li>
<li>31</li>
</ul>
</div>
I'd like to hide everything in .drop-down class excluding <h3> by clicking on <h3>. In this case only .arrow toggleClass works.
Use closest instead of parent
$(this).closest("#categories")
parent will only go back 1 level , i.e, the immediate parent. But you gotta get the container that encloses all the 3 elements
So $(this).parent(".drop-down")
supposed to be either
$(this).parent().parent() // this will break if there is an extra
// parent container gets added
or
$(this).closest("#categories") // This will work even if the no of
// parent container keep chaning
if you need toggle them all but the .drop-down .siblings is just what you need
$("div.drop-down > h3").click(function(){
var $t = $(this);
$t.parent().siblings().toggle();
});
I want to hide all instances of an li element with class parent that have an immediate child div element with class child-1. Here's a pseudocode example, where the method hideParent() would hide the parent of the selected element(s):
$("li.parent > div.child-1").hideParent();
The following is an example of my HTML, in which the second and third li.parent elements should be hidden.
<li class="parent">
<div class="child-0"> ... </div>
</li>
<li class="parent">
<div class="child-1"> ... </div>
</li>
<li class="parent">
<div class="child-1"> ... </div>
</li>
Try this:
$("li.parent > div.child-1").parent().hide();
Select the relevant child elements directly, target their parents (filtered by the relevant selector), then hide them.
$("div.child-1").parent('li.parent').hide();
See:
parent Documentation
Another option is with using filter:
$("li").filter(function () {
var $this = $(this);
var isParent = $this.hasClass("parent");
var childMatchCount = $this.children("div").filter(".child-1").length;
return isParent && childMatchCount;
}).hide();
DEMO: http://jsfiddle.net/GEhfP/
Although this can be optimized in several ways. But to me, it's more "readable", in a very explicit sense. Using jsperf, the quickest I can get filter to work is with:
$("li.parent").filter(function () {
return $(this).children("div.child-1").length;
}).hide();
#Joe's answer was the fastest with: $("li.parent > div.child-1").parent()