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.
Related
I have an HTML like this
<div class="this">
EXP
</div>
I want to add id to <a>. But do not know what to do.
First select your element using something like .getElementsByClassName(). Keep in mind that .getElementsByClassName() returns a NodeList collection of elements, so you'll want to access the first index (or loop over them). You can then simply set the ID with .id, as the ID is merely a property of an element.
This can be seen in the following:
const element = document.getElementsByClassName('this')[0];
element.id = 'element';
console.log(element);
<div class="this">
EXP
</div>
If you want to add this with Javascript, you'll need to use a selector to target your <a> tag and then set the id attribute on it. You can do this by using the querySelector() function or as seen below:
// Find an <a> tag that occurs below a class called "this" and set its id attribute
document.querySelector('.this > a').id = "some-id";
There are many other available functions to handle this through native Javascript and other frameworks, so your milage may vary depending on what you are using.
Example
In this example, we have provided some CSS that should only apply to an element with an id of "test" and we'll run the necessary code to show that the id is being added to the element (as it will be red):
document.querySelector('.this > a').id = 'test';
#test { color: red; }
<div class="this">
EXP
</div>
Add the id attribute to the <a> tag. See the differences of the middle line:
<div class="this">
<a id="expid" href="exp.com">EXP</a>
</div>
I have a Polymer paper-toolbar element that takes some custom attributes like background-color and titles. It contains a.o. a search button and is called in various other elements.
The problem is that only the element where it is first called will display the search box when toggled while in other elements it does not.
This is the code for the toolbar:
<template>
<paper-toolbar class$="{{toolbarSize}}" style$="background-color:{{toolbarColor}};">
<span class="title"><p>{{topTitle}}</p></span>
<div id="searchbox">
<input-search placeholder="Search …"></input-search>
</div>
<paper-icon-button id="searchicon" icon="search" on-tap="openSearch"></paper-icon-button>
<span class="middle title"><h1>{{middleTitle}}</h1></span>
<span class="bottom title"><p class="subtitle">{{bottomTitle}}</p></span>
</paper-toolbar>
</template>
<script>
Polymer({
is: 'tool-bar',
properties: {
topTitle: String,
middleTitle: String,
bottomTitle: String,
toolbarSize: String,
toolbarColor: String
},
openSearch: function() {
var sb = document.getElementById("searchbox");
console.log(sb);
if (sb.hasAttribute("hidden")) {
sb.removeAttribute("hidden");
} else {
sb.setAttribute("hidden", true);
}
}
});
</script>
This is the code that calls in in various other elements:
<paper-scroll-header-panel>
<div class="paper-header staticpage">
<tool-bar
toolbar-color="var(--sc-gold-500)"
toolbar-size="tall"
middle-title="Titletext"
bottom-title="Subtitle text">
</tool-bar>
</div>
<page-view></page-view>
</paper-scroll-header-panel>
When I open the site and click on the search icon, it indeed toggles the searchbox just fine. But when I go to any other page (a different element that calls the same toolbar with different attributes), it does not toggle the toolbar any more.
This looks to me like a bug but if anybody has a solution or explanation for this behavior, I'd be very grateful. I have tried it with various other input-elements and it has the same result.
Output of the Console.log:
The console.log seems to indicate that everything is fine.
On the first page (where the element hides/unhides correctly):
First click: <div id="searchbox" class="style-scope tool-bar" hidden="true">
Second click: <div id="searchbox" class="style-scope tool-bar">
Then I move to another page/element and it gives exactly the same results, except that the element does not hide, even when the attribute hidden="true". When I look at the inspect element however, it does not show the attribute hidden="true".
However, when I click it so the console.log says that hidden="true", and then I move back to the first page/element, the searchbox is indeed hidden on that first page.
Because Polymer is based on Shadow-DOM, standard DOM selectors (such as document.getElementById('someId')) are ill-advised will lead to unexpected results. This is because a custom element will insert duplicate IDs into the DOM.
To overcome this, you must use Polymer's element selector method instead: Polymer.dom(this.root).querySelector('#someId'). This can be conveniently shortened to this.$$.someId. (where this is the custom element)
The Fix
For your code as above, change the openSearch function to the following:
openSearch: function() {
this.toggleAttribute('hidden', true, this.$.searchbox);
}
Thanks #Kuba for pointing out my initial error.
Fix Explanation
Element Selection
this.$ is an object of element IDs for the current custom element (this) when it was stamped onto the page. Therefore, this.$.searchbox gets the element's handle for this custom element's 'searchbox' element. This is in comparison to document.getElementById(...), which will only get the first element with id="searchbox" it finds on the page, not necessarily the one belonging to the current custom element.
Attribute Toggling
Polymer adds some special methods to it's element handles (that come from PolymerBase) for custom elements. One of these is the PolymerBase.toggleAttribute(String name [, Boolean value, Element node]) method (link to docs). To use this method with a polymer element, you call it on the element's reference from this.$ or this.$$.
For elements of a custom element, use:
this.toggleAttribute('hidden', true, this.$.someElementId)
If the target element is a custom element loaded by polymer, you can also use:
this.$.someElementId.toggleAttribute('hidden')
this.$.someElementId.toggleAttribute('hidden', true)
As a side note: Please rename your toolbar to vims-toolbar or similar to follow the custom elements naming scheme of <namespace>-<element-name>.
Further reading: PolymerBase docs
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'});
My html looks like this
<a class="jx_ui_html_a" target="_blank" __jx__id="___$_2854__a" href="https://www.kitty.com">
<div class="jx_ui_html_div path_title" __jx__id="___$_2854__path"></div>
</a>
and
i am trying to find a greasemonkey script which changes the href part from ANYTHING to https://www.dog.com if the A class is jx_ui_html_a
so the result should be
<a class="jx_ui_html_a" target="_blank" __jx__id="___$_2854__a" href="https://www.dog.com">
<div class="jx_ui_html_div path_title" __jx__id="___$_2854__path"></div>
</a>
respectively
<a class="jx_ui_html_a" target="_blank" __jx__id="___$_28254__a" href="https://www.dog.com">
<div class="jx_ui_html_div path_title" __jx__id="___$_28254__path"></div>
</a>
Could you please help me in any way?
The following is two lines of code - the first one queries the DOM to find all a tags (document.querySelector('a') and converts it into an array (by passing it as an argument to [].slice.call), and the second runs a forEach function on the array, which reassigns the href attribute of every DOM Element in the array.
var anchors = [].slice.call(document.querySelectorAll('a');
anchors.forEach(function(element){
element.href = "http://www.dog.com/"
});
Same thing without forEach:
var anchors = document.querySelectorAll('a');
for(var i=0;i<anchors.length;i++){
anchors[i].href = "http://www.dog.com";
}
To limit the elements of anchors to only those with specific class name, supply it as part of the querySelector argument:
var anchors = document.querySelectorAll('a.jx_ui_html_a')
querySelector and querySelectorAll select elements the same way that rendering engines which apply CSS rules do. So you can pass it things like "p > a" (will return 'a' elements that are direct descendants of 'p' elements), and "div#container span" (which will return span elements that are anywhere inside the div with 'container' id).
querySelector returns the first match, while querySelectorAll returns an array-like list of all matching elements.
First you'll want to require jQuery. You can read about how to do that here.. Once that's installed you can run something like the following:
$(document).ready(function() {
$('.jx_ui_html_a').attr('href','http://www.dog.com');
});
In English, that will wait until the page is fully loaded ($(document).ready()), search for all elements with your specified class ($('.jx_ui_html_a')), and replace all of their href attributes with your specified URL.
How do i even put these, let me try. In the following sets of codes, i want to click 'parentclass' and have an alert value of 'child1' and when i click the class below it which is 'Parent 2' have an alert fire with a value of 'child2'
So this must alert the content of that class only and not the entire class.
Here's some Javascript in Jquery.
var childclass = $('.childclass').html();
$('.parentclass').click(function(e) {
alert (childclass)
});
$('.childclass').click(function(e) {
e.stopPropagation()
e.preventDefault()
});
And HTML
<a href="" onClick="return false">
<div class='parentclass'>
Parent 1
<div style="display:none" class="childclass">child1</div>
</div>
</a>
<a href="" onClick="return false">
<div class='parentclass'>
Parent 2
<div style="display:none" class="childclass">child2</div>
</div>
</a>
This line var childclass = $('.childclass').html(); doesnt make sense as it doesn't know which element in particular you mean. The result of that will just be child1child2 which is just a concatenation of the .html() of all the elements with class childclass. This is obviously not what you want.
Therefore you should dynamically find the child with a class of childclass upon receiving the click event.
$('.parentclass').click(function(e) {
alert($(this).find('.childclass').html())
});
Also, you should know that your child class event handler is useless as we don't care if the event gets propogated downwards. If you DID care, then your e.stopPropagation() and e.preventDefault() should be in the event handler of the parent class.
You need to fetch the html of the clicked parent element within the click handler
$('.parentclass').click(function (e) {
alert($(this).find('.childclass').html())
});
$('.childclass').click(function (e) {
e.stopPropagation()
e.preventDefault()
});
Demo: Fiddle
Several ways you can go about this.
First, if your HTML will not be dynamic (elements already exist when page loads), then you can select elements by the parent class name and assign click event as so:
$('.parentclass').click(function(e) {
// the first variable here is selecting the inner elements having class 'childclass'
// keep in mind, if more than one child having that class is present within this parent, it will select all of them
var child = $(this).find('.childclass');
// here we alert the text of the inner child found
// if it is more than one, you will have undesired results. you may want to specify `.first()`
alert(child.text())
})
For newer jQuery you can also use $('.parentclass').on('click', function(e) {.
If you expect any pieces of parentclass to be dynamic, then you'll want to delegate the event based on either a static parent to the parents or document. This can be like so:
$(document).on('click', '.parentclass', function(e) {
alert($(this).find('.childclass').text())
})
Or, if you have a static (already there when page loads) wrapping element, give it an ID like `parentClassWrapper' and assign the click event dynamically as:
$('#parentClassWrapper').on('click', '.parentclass', function(e) {
alert($(this).find('.childclass').text())
})
Some helpful links:
jQuery API
jQuery Selectors
.click()
.on()
Some info on Event Delegation
jquery on vs click methods
jQuery .on('click') vs. .click() and .delegate('click')
jquery .live('click') vs .click()
I made several adjustments to your html that are worth noting. There's no need for the <a> tag. Don't use inline js - onlick in your html. Note that I wrapped the text inside of the div in the <a> tag instead. This markup is more semantic. Also, move your styles to css rather than in the html.
<div class="parent">
<a>Parent 1</a>
<a class="child">child of parent 1 contents</a>
</div>
<div class="parent">
<a>Parent 2</a>
<a class="child">child of parent 2 contents</a>
</div>
css:
.parent > .child { /* good practice: only select an immediate child of the parent */
display: none;
}
The other answers here are using find() to select the child, but I recommend children() instead. For example, if you had additional nested .childs, find() will select them all, but children() will only select direct .childs of the parent, so it is better in this case. I also recommend using the console for debugging rather than alert.
Live demo here (click).
$('.parent').click(function() {
var $child = $(this).children('.child');
var cls = $child.attr('class');
console.log(cls);
$child.show(); //added so that you can click the child
});
$('.child').click(function() {
var html = $(this).html();
console.log(html);
//if you just want the text, use this instead:
var text = $(this).text();
console.log(text);
});