javascript/jquery select all child elements inside a parent element - javascript

I have a bunch of child elements that are uniquely identified within a parent div. I want to know if there's a way in jQuery (or javascript) to capture all of them? The number of children in the parent div is arbitrary, meaning it could be any number for each div. For example:
<div class="parent1">
<span class="child1">some text here</span>
<span class="child2">some other text</span>
...
<span class="child49">yet more text</span>
<span class="something_else">other text i don't want to select</span>
</div>
<div class="parent2">
<span class="child1">some text</span>
<span class="child2">some text</span>
...
<span class="child120">some text</span>
</div>
So considering the above example, how do I get ALL the children (.child1 through .child49) within the class parent1?
I know that doing the following will work in jQuery (using multiple selector):
$(".child1, .child2, ..., .child49").css("background","red");
But is there a better way? I won't always know how many children are in each parent.
EDIT: also, I might have other children in the parent with a different class name that I DO NOT want to select; I specifically want to select all the "child*" classes.

$('.parent1 span[class^="child"]')
will select all the spans that start with the class child under the class .parent1.
If you want all the span.childX under all parentX then use:
$('div[class^="parent"] span[class^="child"]')
This is using a CSS3 attribute selector which jQuery have implemented (and extended in some cases). From the documentation:
E[foo^="bar"] an E element whose "foo" attribute value begins exactly with the string "bar"

These codes gets all child in div.parent1 and div.parent2
$('[class^="parent"] span').css({ });
$('[class^="parent"]').children().css({ });
Thess codes gets onli the children for parent 1
$('.parent1 span').css...
$('.parent1').children().css...

use .children along with .filter, if number of children are not certain then label all childs which you want to manipulate of parent1 as child1
$(".parent1").children().filter(".child1").css({color:'Red'});
here is the fiddle http://jsfiddle.net/8hUqV/1/
jquery children

Related

How to select the last child inside the tree using jQuery?

Suppose I have such a structure:
<div id="content">
<div>
<span>
<b>
<i>
<u>
<span>Price</span>
</u>
</i>
</b>
</span>
</div>
</div>
In this case, the number of tags inside the div #content and which ones they don't know me. I only have access to the id content.
How do I get the selector to the latest span which contains the text Price?
p.s. lastChild method returns the last child within the selected selector, but not deeper!
Select all children of #content using * selector and use .filter() to filtering element. In callback filter elements hasn't any child.
$("#content *").filter(function(){
return $("*", this).length == 0;
});
// Or using ES6
$("#content *").filter((i,v) => $("*", v).length == 0);
var ele = $("#content *").filter((i,v) => $("*", v).length == 0);
console.log(ele[0].outerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<div>
<span>
<b>
<i>
<u>
<span>Price</span>
</u>
</i>
</b>
</span>
</div>
</div>
You can use .find():
https://api.jquery.com/find/
This will recursively look for your selector, so:
$('#content').find('span') will give you two spans, one for the first nested span and one for the second nested span. The downside is that if you have multiple spans you'll need to find the right one.
If you can put an identifier in the last one, say a class named 'target-class', than you know you'll find the right one:
$('#content').find('span.target-class');
First of all let's fix your syntax. You can't put an <span> directly within a <u>. You need a <li> node. Also you can't/shouldn't put block elements such as ul within inline elements (span, a, b, i...). And even <b> and <i> are not recommended, better use semantic markup such as <strong> or <em> instead.
Now your problem. I think you don't have to care about being the last node. If you know the text contained is "Price" you can look for it in the following way:
var selector = $('#content').find(":contains('Price')");
$(selector).addClass('highlighted');
.highlighted {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<div>
<u>
<li>
<span>Price</span>
</li>
</u>
</div>
</div>
If this solution does not fits your needs, to get the last node you have to get all of them an check if they have children or not. Once they don't, you've reached your target.
But I have to say that this is a solution you could have found in SO.
Select deepest child in jQuery
Jquery Way -
You could target all spans $() and target the latest span using slice() method.
$('#content span').slice(-1)[0];
Javascript way -
Find all spans using querySelectorAll(), You'd get a NodeArray, you can convert it to Array using Array.from() and slice() last item from it which is latest span.
Array.from(document.querySelectorAll('#content span')).slice(-1)[0]

How to find a root element that contains specific text using nested id

I would like to select a root element that contains a specific text using nested div id in Query. For example:
<div>...
<div id="parentDiv1">
<span>
....
<span>
.....
<div>..</div>
<div id="myId1">...</div>
</span>
....
</span>
</div>
</div>
<div id="parentDiv2">
<span>
....
<h2>..</h2>
<span>
.....
<div>..</div>
<div id="myId2">...</div>
</span>
....
</span>
</div>
Now, I need to select a div which has the id parentDiv with a nested div having id #myId1.
I find more difficult in this case. I know this is a complex case. Can anybody help me please.
Assuming I'm understanding the question correctly, this should work:
$("div:contains('parentDiv')").has("#myId1");
or if you need just the id of the div with those attributes:
$("div:contains('parentDiv')").has("#myId1").attr('id');
For more info check out:
Jquery :contains selector

How to select certain class in jQuery

Here's the problem; I have a couple of divs like the one below, same class name, no id. I need to modify the <span> text below the <h4> tag, based on where's the mouse cursor on those 3 images. I do this using javascript, by using mouseenter() method. The problem is that the method changes every span text from whole web page, not only from the class with class name "parent" where the mouse cursor is at the moment.
<div class="parent">
<div class="parent.child">
<div class="parent.chil.child">
<div class="parent.chil.child.child">
<img src ="link1" data-price="a">
<img src ="link2" data-price="b">
<img src ="link3" data-price="c">
</div>
</div>
</div>
<h4>
text
</h4>
<p><span class = "spanClassName">text to be changed</span>some text</p>
<div class=child1"></div>
</div>
How do I select only the link where's the mouse, from the curent "parent" div, even if there are several div with same class name, "parent".
I hope I was understood, if not, please ask and I try to explain more.
You can use .closest() to find parent with .parent class
$('.parent\\.chil\\.child\\.child img').on('hover', function(){
$(this).closest('.parent').find('.spanClassName').text($(this).attr('data-price'))
});
DEMO
Additionally as per documents you need to escape . in your selectors
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?#[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").
If you already know the specific parent node, just use parent.find('.spanClassName'). If you don't have the parent node, but you know which link the mouse is on, you can use link.closest('.parent').find('.spanClassName').

JS Only apply if condition to relevant item

I have a small group of items as shown below.
<div class="item">
<div class="date">2013-08-08</div>
<div class="headline"><a data="normal" href="#">Title</a></div>
</div>
<div class="item">
<div class="date">2013-10-08</div>
<div class="headline"><a data="special" href="#">Title</a></div>
</div>
If the title has a data attribute of special, I want to make the date bold for that item only.
I have the below code to try and do this.
<script>
if ($(".headline a [data='special']")){
$( ".date" ).wrap( "<b></b>" );
}
</script>
However this makes all items bold if the condition is true.
I am familiar with using this in JS but not sure how to relate it to another div above.
What is the best way to do this?
I am happy to change the html structure if required as well.
Try the following:
$(".headline a[data='special']").parent().siblings(".date").wrap("<b></b>");
The parent() function will select the div.headline for a matching <a> tag; then, siblings(".date") will select children of the parent of div.headline (which are called siblings) that have the date class.
It sounds like you'd like to select the .date element in .item elements which contain .headline a[data="special"] elements.
$('.item:has(.headline a[data="special"]) .date')
will select the correct .date elements for my given assumptions, you can then call .wrap('<b></b>').
Also note: [data] is not a valid [data-*] attribute. You must have a hyphen and a name for custom data attributes.

Understand JQuery Selector expression

I am trying to read some JavaScript that is selecting element(s) using this expression
$("body > div:not(.layout-ignore):not(.ui-loader)")
I get that its starting at the body but is that the Greater Than (>) symbol saying select all div elements within the body element that do not have .layout-ignore and also not .ui-loader class attributes?
Can anyone explain to me this syntax? Also point me to some online documentation that helps me further understand this selector expression.
Cheers
jQuery uses CSS selectors as its basis. The MDN has an extremely thorough guide as to what these are and how they work.
Please see here: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors
and here: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started
In your example it means any div (that is not of class .layout-ignore or .ui-loader) that is a child of body. Meaning nested divs would not be selected.
Hope this helps.
...is that the Greater Than (>) symbol saying select all div elements within the body element that do not have .layout-ignore and also not .ui-loader class attributes?
The > is saying that the div that matches must be an immediate child of body. It's called a "child combinator". So the only div elements that can possibly match are immediate children of body, they can't be inside another intermediate element. So:
<body>
<div><!-- This div matches the selector -->
<div><!-- But this div does not --></div>
</div>
</body>
The two :not qualifiers (which are the "negation pseudoclass") are saying that the div cannot have the class layout-ignore and cannot have the class ui-loader.
So in total:
<body>
<div><!-- This div matches the selector --></div>
<div><!-- But this div does not, it's not a direct child of body --></div>
</div>
<div class="layout-ignore"><!-- This does not because it has layout-ignore --></div>
<div class="ui-loader"><!-- And neither does this, because it has ui-loader --></div>
</body>
The body > div code is select all div that are direct children of body (http://devdocs.io/css/child_selectors)
<body>
<div>first</div>
<span>
<div>second</div>
</span>
</body>
(ignore that the html markup isn't valid here) but with that selector it will only select the div with the text first.
the :not selector will exclude everything within it: http://api.jquery.com/not-selector/
<body>
<div>first</div>
<span>
<div>second</div>
</span>
<div class="example"></div>
</body>
body>div:not(.example) with the body>div it will select both the "first" div and the .example but will exclude .example div from the collection.

Categories

Resources