How can I check closest parent classname in angular 6? - javascript

I want to check classname which the closest parent of the clicked element in angular 6?
HTML
<div class="parent-element selected" (click)="checkClass($event)">
<ul>
<li><a>Link-1</a></li>
<li><a>Link-2</a></li>
<li><a>Link-3</a></li>
</ul>
</div>
ANGULAR
checkClass(element) {
return element.target.classList.contains('selected');
}
if I check the classname by using "checkClass" function, it doesn't always give the right result, because there is a possibility of clicked element other than a parent. So I want to first find the closest parent of the clicked element and than check the classname. How can I do that?

$event.target.parentNode; will give you parent element.
you can get parent element by this:
$event.target.parentElement
and all the class list by this:
$event.target.parentElement.classList;

Related

Puppeteer - get parent element

I'm trying to click on one value (odds) based on the name of the other element but those two need to be inside a specific parent element which I get by the text inside it.
The snippet below can be found multiple times on the same page with the same classes so targeting by class is not an option.
I first need to get a container with text "1st Goal. Then I need to get it's parent and in the parent, I need to get the second div element (class parent2). That element holds other elements. Let's imagine I need to get the element of value 200 and click on it.
I've tried using parentElement, parentNode but always get the 'undefiend' when getting a parent of the child element, although the child element is retrieved successfully. I just can't get the parent from where I could go down the tree to the desired element and click on it.
<div class="group ">
<div class="parent1 "><span>1st Goal</span></div>
<div class="parent2">
<div class="container ">
<div">
<div><span>Malaga</span><span class="odds">200</span></div>
<div><span>No 1st Goal</span><span class="odds">300</span></div>
<div><span>Las Palmas</span><span class="gll-odds">400</span></div>
</div>
</div>
</div>
<div></div>
</div>
XPath expressions
If you are okay with using XPath expression, you can use the following statement:
//div[contains(#class, "group") and contains(., "1st Goal")]/div[#class="parent2"]//span[#class="odds"]
This XPath expression queries for a div element having the class group and containing the text 1st Goal somewhere. Then it will query the children div with the class parent2 and query span elements with class odds inside.
Usage within puppeteer
To get the element with puppeteer, use the page.$x function. To click the element, use elementHandle.click.
Putting all together, the code looks like this:
const [targetElement] = await page.$x('//div[contains(#class, "group") and contains(., "1st Goal")]/div[#class="parent2"]//span[#class="odds"]');
await targetElement.click();
const parent_node = await child_node.getProperty('parentNode')
You can try this one

How to replace all id from href?

I have the following markup
<div class = "general">
<div id ="custom"></div>
</div>
How to change id = "custom" in all <div> with class="general" from href on page using jQuery?
You can try this:
$("div.general").each(function() {
$(this).children("div#custom").text($(this).children("a").attr("href"));
});
If I understand you correctly, you want to iterate through all div.generals, and change the text of each child div#custom to the href of the child a.
See a working example on JSfiddle.
Also, another tip is to avoid using multiple elements with the same id. In your code you have a <div> with id="custom". You also say that the div.general appears multiple times — therefore, the id "custom" will appear multiple times. This is bad practice. I suggest that you change id to class.
You need to loop through all div.general and replace the id attribute of div#custom to whatever is there as the anchors href property. The following code will work:
$(".general").each(function(){
$(this).find("#custom").attr("id", $(this).find("a").attr("href").replace("#", ""));
})
Here the .find() will dig out elements from any depth inside the parent. If you are sure about the DOM position of the elements, you can change the .find() to .children()

When a Div class is clicked, alert it's inner content's Div Class

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

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.

Selecting a division based on what division it using Jquery

<div class = ui-dialog-abc ui-dialog-xyz>
<div id = "sheet1abc">
</div>
</div>
<div class = ui-dialog-abc ui-dialog-xyz>
<div id = "sheet1xyz">
</div>
</div>
<div class = ui-dialog-abc ui-dialog-xyz>
<div id ="sheet2foo">
</div>
</div>
<div class = ui-dialog-abc ui-dialog-xyz>
</div>
Can I select a div based on what div it contains? I want to make the div containing the div whose id contains sheet1 visible or hidden.
If I've understood you correctly, you are looking to select the div that is a parent of a div with an id beginning with "sheet1".
If that's correct, you can do the following:
$("div[id^=sheet1]")
That will select all div elements with an id beginning with "sheet1". You can then loop through the set of elements using each and get the parent of each element to access the parent div.
Once you have the parent div, you can show/hide it using show or hide.
See an example fiddle in which I alert the id of the each matching parent div.
Update
If the child div you are looking for is not a direct child of the ancestor div, you can use parent().closest('div') to climb the DOM tree to find the first ancestor div of the div with your id.
The question asks to get the "div containing the div...", so this method will get the first ancestor div. See this fiddle, in which the child div is contained within a table.
$('div').has('div[id="sheet1abc"]').text();
$('div').has('div[id="sheet1xyz"]').text();
Grab all divs whose ids contain 'sheet1', then grab their closest containing div:
$('div[id*=sheet1]').map(function() {
return $(this).parents('div:first')[0]
});

Categories