Access specific child div with jQuery - javascript

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" )

Related

How to get all the "a" elements inside this div?

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>

How to select leaf node using jQuery :contains selector?

I want to get leaf elements containing specific text, and I used :contains selector. However, this selector selects includes every parent nodes too. Here is my example.
<div id='parent1'>
<p id='target1'>Red balloon</p>
<div id='target2'>Blue balloon</div>
</div>
<div id='parent2'>
<span id='target3'>Brown balloon</span>
</div>
In this case, I just want to get elements containing text balloon. I expected to get 3 elements(target1, target2, target3) by $(":contains('balloon')"), but it returns every nodes including parent nodes of targets. (e.g. html, body, and every parent div)
How can I select only targets?
p.s Above HTML is only example. HTML can be vary, so the answer should be generic.
use indexOf("balloon") > -1 to find id the word balloon is found
var arr = $("div").children().map(function(){
if($(this).text().indexOf("balloon") > -1 )
return $(this).attr("id")
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent1'>
<p id='target1'>Red balloon</p>
<div id='target2'>Blue balloon</div>
</div>
<div id='parent2'>
<span id='target3'>Brown balloon</span>
</div>
The solution below, look for all elements containing the word and clone these elements, This way we can be sure only to get "correct" amount of elements
Just remove .length and you have access to the elements.
var s = $(":contains('balloon')").not("script").filter(function() {
return (
$(this).clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.filter(":contains('balloon')").length > 0)
}).length;
console.log(s)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent1'>
<p id='target1'>Red balloon</p>
<div id='target2'>Blue balloon</div>
</div>
<div id='parent2'>
<span id='target3'>Brown balloon</span>
</div>

Unable to access descendant of an HTML element using jQuery

I have a problem with getting a html() value of child of a parent :D
function voteup(e){
var count = $(e).parents('.item').children('.count');
console.log(count.html()); // undefined
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post_contain">
<img src="images/comments/dQ6dz.jpg" alt="">
</div>
<div class="item">
<p class="post-meta">
<span href="/gag/agVzE1g" target="_blank">
<span class="count">5</span>points
</span>
</p>
<div class="vote">
<ul class="btn-vote left">
<li class="badge-item-vote-up-li">
<a onclick="voteup(this)">Click me</a>
</li>
</ul>
</div>
</div>
In the function voteup(e), I need to get the value of the class 'count', but I don't retrieve the value with html()
children only traverses a single level of the DOM tree - i.e. it won't find grandchildren.
Instead, use closest to find the .item -- which finds the single nearest match, as opposed to parents which can find multiple -- and find to locate the child, since that will traverse arbitrarily deep HTML structures:
function voteup(e){
var count = $(e).closest('.item').find('.count');
alert(count.html());
var actual = parseInt(count.html(), 10);
count.text(actual + 1);
}

How to include negation in this JQuery selector?

I have the following HTML fragment.
<div class="diagram-frame">
<div class="diagram">
<span class="diagram-name">Drawing Objects</span>
<svg>...lots of child elements...</svg>
</div>
<div class="diagram-name">
<a class="idlink" title="Drawing Objects (data models)" href="...">NA - Drawing Objects</a>
</div>
</div>
Currently, I use this jQuery selector to detect what has been clicked on:
jClicked.add(jClicked.parents()).is('div.diagram-frame')
jClicked is jQuery object containing the clicked element.
But I need to exclude clicks on the diagram-name div. How can I add negation using the .not('div.diagram-name') function call?
Since .is() matches a css selector, why not use the css :not() pseudo, and do all in one command?
jClicked.add(jClicked.parents()).is('div.diagram-frame:not(.diagram-name)')
Like this?
jClicked.add(jClicked.parents())
.not(jClicked.$('div.diagram-name'))
.is('div.diagram-frame')
Note, Not certain about jClicked object ?
Try
$(function() {
var jClicked = [];
$(".diagram-frame").on("click", function(e) {
if (!$(e.target).parent().is("div.diagram-name")) {
jClicked.push(e.target);
console.log($(jClicked));
alert(jClicked.length);
}
});
});
$(function() {
var jClicked = [];
$(".diagram-frame").on("click", function(e) {
e.preventDefault();
if (!$(e.target).parent().is("div.diagram-name")) {
jClicked.push(e.target);
console.log($(jClicked));
alert(jClicked.length);
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="diagram-frame">
<div class="diagram">
<span class="diagram-name">Drawing Objects</span>
<svg>...lots of child elements...</svg>
</div>
<div class="diagram-name">
<a class="idlink" title="Drawing Objects (data models)" href="...">NA - Drawing Objects</a>
</div>
</div>
jsfiddle http://jsfiddle.net/guest271314/2myjbuhL/

jQuery - Add class to parent container based on content of child container

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');
});

Categories