How to apply CSS on parent using its child - javascript

Hello I want to apply CSS on parent using its child
<li>
<div>
<label>
<b style="display: none;">Name and Date of Event*: </b>
</label>
</div>
</li>
I want to hidden to list. but I don'n know how to Apply CSS.
I used just
jQuery("b:contains('Name and Date of Event*:')").css('display','none');
But it hidden only <b> Tag I want to hide li.
How can I hide parent li using child.Is it Possible.

Use .closest() function. It accepts a selector and finds the the appropriate ancestor.
$('#btn').on('click', function(){
$("b:contains('Name and Date of Event*:')").parents('li').css('display','none');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
Li Content
<div>
<label>
<b style="display: none;">Name and Date of Event*: </b>
</label>
</div>
</li>
<button id="btn">Hide li</button>
Why use .closest and not .parents ?
.closest()
Begins with the current element
Travels up the DOM tree until it finds a match for the supplied selector
The returned jQuery object contains zero or one element for each element in the original set
.parents()
Begins with the parent element
Travels up the DOM tree to the document’s root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
The returned jQuery object contains zero or more elements for each element in the original set

You can apply .parents() OR .closest()
Try this
jQuery("b:contains('Name and Date of Event*:')").parents('li').css('display','none');
OR
jQuery("b:contains('Name and Date of Event*:')").closest('li').css({'display':'none'});

Related

jQuery.contains() returns wrong ouput

Am trying to use jQuery.contains(parent,child) to check if an element is a child of another the evaluation of the function returns true, eventhough the 2 elements are not subsequent, please find it on jsfiddle
HTML
<button onclick="clickme()">Click me</button>
JS
function clickme() {
parent = $("#parent")
child = $("#child")
alert(jQuery.contains(parent,child))
}
the parent element has the following attributes
<li id="parent"><a class="dropmenu" selectdropvalue="8" geolocation="IN" href="javascript:void(0);" redirect="https://www.rohm.co.kr/">한국 - 한국어</a></li>
the child element am checking has the below
<span>
<a style="width: 156px; display: block;" href="javascript:void(0);" id="portals-button" class="ui-selectmenu headlang">
<span class="ui-selectmenu-status" id="child">Europe - English</span><span class="ui-selectmenu-icon"></span>
</a>
</span>
is that the correct way to use it ?
From https://api.jquery.com/jQuery.contains/ :
The $.contains() method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply.
So it will still return true if I'm interpreting your screenshots (avoid that btw!) correctly: <span> is child element of <a>, which is child element of <li>, and you are using contains(element li, element span).
Edit considering your latest edit and jsfiddle:
From https://api.jquery.com/jQuery.contains/ :
Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.

How to recursively select all children under an element Javascript

I need a function that recursively selects all child elements but wont select elements (and those elements children) if they have the "foo" attribute.
<section>
<div>
<span foo>
<input>
</span>
</div>
<p>
<img>
</p>
</section>
//should return [section, div, p, img]
I need raw Javascript please
edit:
I tried something like this:
$tag.querySelectorAll(":not([foo])")
but querySelectorAll(":not([foo])") will still return the children of the unselected element.
You can use element.querySelectorAll() with the :not modifier here, together with the [attr] selector:
var nonFooElements = parentElement.querySelectorAll("*:not([foo])");
Be aware that this sort of call will be moderately expensive because the selector doesn't begin with an id or a classname, so don't do huge amounts of it.
I adapted this answer from this one: https://stackoverflow.com/a/21975970/5009210

Delete closet image with class jquery

Need to remove the image src of the closet img with a class and set it to hidden. This is what i have tryed so far.
<img class="img-preview" src="http://www.abmuku.com/wp-content/uploads/2012/04/google-logo-small.jpg" />
<span> random stuff here </span>
<button class="delete"> Delete
</button>
$('.delete').on('click', function(){
$(this).closest('.img-preview').remove();
console.log("ha")
});
http://jsfiddle.net/tQ5vr/38/
Use .prev() instead of .closest()
$(this).prev('.img-preview').remove();
.closest()
Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing
up through its ancestors in the DOM tree.
.prev()
Description: Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it
retrieves the previous sibling only if it matches that selector.
to change the src and hide it you can use
$(this).prev('.img-preview').attr('src','').hide();

jQuery select child of closest element

Basically I want to be able to select the div level2 parent from the child level4 div. My application does not has such classes, otherwise I'd just select level2 :)
<div class="level1">
<div class="level2">
<div class="level3">
<div class="level4"></div>
</div>
</div>
<div class="level2"> <!-- this is hidden -->
<div class="level3">
<div id="start" class="level4"></div>
</div>
</div>
</div>
I start with $('#start') and search for the first parent which is visible, but I'm not seeing a way to return the child of that parent. Searching for $('#start') inside the parent seems very wasteful as I start with a sub child to begin with.
$('#start').closest(':visible') // returns level1
$('#start').closest(':visible').first() // returns the first level2. I can't just use second because the number of level2s can change.
$('#start').closest(':visible').children().each(function(){ /* do some search to check it contains `$('#start')` }) // seems very wasteful.
Another way to look at what I'm trying to say would be; start in the middle, find the outside (the visible element), and move one element in.
How about this:-
$('#start').parentsUntil(':visible').last();
This will give you all hidden parent div's until its visible parent and last() wil give the outermost parent which is hidden. last is not a selector on position it is the last() in the collection.
You want the .has() method
Description: Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
$('#start').closest(':visible').children().has('#start');
See fiddle for example.
You say that the classes don't exist...why not add them? It would make thinks much easier to find. The class names don't need to have actual styles associated.
var allLevel4 = $('#start').closest(':visible').find('.level4');
var firstLevel4 = $('#start').closest(':visible').find('.level4')[0];
var secondLevel4 = $('#start').closest(':visible').find('.level4')[1]; //also, #start
Use .filter():
$('#start').closest(':visible').children().filter(':first-child')
.find() is also good for selecting pretty much anything.

Is Id necessary in applying jquery functions?

Suppose I have two p tags in the document. I want to call two different effects using jQuery when onMouseOver event happens. Is it necessary that these two p tags be given Ids. Can't it be achieved without giving Ids to these tags ?
You don't have to give anything an id, however it is the best way to uniquely identify an element.
You can instead idenfity by class:
$(".myClass")
By attribute:
$("[src='image.jpg']")
By position in parent:
$("p:eq(2)")
A full list of selectors is available in the documentation
$('p:first'); // first p tag
$('p:last'); // last p tag
$('p').eq(1); // exactly the second p tag
There are several ways to select an element / elements:
$('.classname')
$('#id')
$('tagname')
$('[attr="value"]')
etc
although jQuery allows you to write faster and easier scripts, but unfortunately it makes you never understand the real JavaScript.
$("*") //selects all elements.
$(":animated") //selects all elements that are currently animated.
$(":button") //selects all button elements and input elements with type="button".
$(":odd") //selects even elements.
$(":odd") //selects odd elements.$("p") selects all <p> elements.
$("p.intro") //selects all <p> elements with class="intro".
$("p#intro") //selects the first <p> elements with id="intro".
$(this) //Current HTML element
$("p#intro:first") //The first <p> element with id="intro"
$("p:eq(2)") // The third <p> element in the DOM
$(".intro") //All elements with class="intro"
$("#intro") //The first element with id="intro"
$("ul li:first") //The first <li> element of the first <ul>
$("ul li:first-child") //The first <li> element of every <ul>
$("[href]") //All elements with an href attribute
$("[href$='.jpg']") //All elements with an href attribute that ends with ".jpg"
$("[href='#']") //All elements with an href value equal to "#"
$("[href!='#']") //All elements with an href value NOT equal to "#"
$("div#intro .head") //All elements with class="head" inside a <div> element with id="intro"
jQuery – Select element cheat sheet

Categories