Target sub element of This Object in jQuery? - javascript

How can I get a sub element from $(this)?
So for example, how would I target a span element within the this object?

You could use the find method:
$(this).find("span");
That will find all span elements that are descendants of the element referred to by this.
If you only care about direct children you could use children instead:
$(this).children("span");
Alternatively, you could use this as the context to a selector:
$("span", this);
Yet another solution would be required if this was a jQuery object that contained a set of sibling elements (so the span is not a descendant). In that case, you would need filter:
$(this).filter("span");

Related

How do you add an element to a class (through JavaScript)?

Suppose that I want to add a newly created paragraph (using document.createElement("p")) into an existing div (with class name "container") in one of my html files. Is there a way to do this by calling some methods?
Since there's a getElementById() method, I figured I would use a getElementByClassName() method too, but that doesn't exist; what exists is getElementsByClassName() instead. One way I can get around this is to just change my div to have an id rather than a class name, and use the getElementById() to add the paragraph into the div, but I wanted to know if there was some method that I could call that would help me retrieve a class element (rather than the elements within the class itself).
I've tried looking for this online, but what I've found are answers to "how to add class names to elements" instead, which is not what I want to know.
For one element, this will chose first in DOM order:
var p = document.createElement("p");
p.innerHTML = "p element";
document.querySelector(".container").appendChild(p);
<div class="container">container</div>
For all elements with chosen class:
[...document.querySelectorAll('.container')].forEach(el => {
var p = document.createElement("p");
p.innerHTML = "p element";
el.appendChild(p);
})
<div class="container">container</div>
<div class="container">container2</div>
HTML DOM elements' IDs have to be unique within a document - and so asking for an element by Id will return you just one element (or null if there isn't a matching element).
However a class name can be applied to multiple elements, so you would expect to get zero one or more elements when searching by class, hence the getElementsByClassName returns a collection.
So if you have a list of elements with the class name container, and you know your document (hopefully) only contains one element with that name, you can pick the first element returned by the getElementsByClassName - e.g. getElementsByClassName('container')[0]
Note - getElementsByClassName returns all elements to which the class has been directly applied, for the children of the element on which it is being called. I've interpreted your query as relating to the whole document in the context of your original question.

Get all elements that contain a particular descendant

I'm trying to loop through all <li> tags that contain the class .fas using the jQuery contains() method and perform some stuff on each one.
$('li:contains(".fas")').each(function (index) {
//stuff
}
I keep getting the reference error that contains is not defined. Am I using this method incorrectly?
You want has().
$('li:has(".fas")').each(function (index) {
//stuff
}
https://api.jquery.com/has/
Another way to do this would be to flip your logic.
$('.fas').closest('li');
You could find all the fas and then find their parent lis.
Your question ambiguity leaves me to cross answer this.
First off:
$('li.fas')
That says to the sizzle engine: Get all elements that have class fas, then reduce that to elements of li (that have that class)
With a space in between this says:
$('li .fas')
Get all elements that have a class fas, then reduce to those that are a decedent of an li element.
$('li>.fas')
Get all elements that have class fas, then reduce that do a set that are direct children of an li element.
The other answer has the .has() so I will not repeat that.
Filter: (basically same as :has() in this case
$('li').filter(function(){
// reduce the li set; return true when a descendant has the 'fas' class
return !!$(this).find('.fas').length;
});
More on context here: https://stackoverflow.com/a/16423239/125981

Select node from children by attribute

I have an interface that switches between displaying different div elements. When it switches which element it displays, I need to access a specific child node of that div element, with each div element having their children arranged differently.
The childNodes and children property both return an object that can only select children with item(index) which is annoying to use as the relevant child element's index is different in each div. For Protractor, I used the webmanager.by(selector) which was able to search with other parameters than index. Is there something similar I can use to select the child node with data-relevant="true". I am also unsure if that attribute is the best way to specify in the HTML which child node is relevant.
This is an Angular application if that helps.
If you want to select the child node with data-relevant="true" from some parent element, you could use the selector method
element.querySelector()
That would return the first matching element...
in your specific case it could be something like
parent-element.querySelector( "[data-relevant='true']" );
or if you want to select all paragraphs p with the data-relevant attribute value true within the parent div: parentDiv.querySelectorAll( "p[data-relevant='true']" );
You can find some examples on
http://www.w3.org/TR/selectors-api/#processing-selectors
An alternative would be to use a special class to identify which child node is relevant...
you could get this element/or many elements with getElementsByClassName(someClassName)
Code Sample With .querySelectorAll() method:
<script type="text/javascript">
window.addEventListener("load", init, false);
function init(){
var parentDiv = document.getElementById("divWithChildren");
var relevantChildren = parentDiv.querySelectorAll( "[data-relevant='true']" );
alert (relevantChildren[2].id); // this will give the id of the 3rd child element with data-relevant='true'
}
</script>

count elements of a class within another class

What is the best way to count elements of a particular class within another element?
I have the class of the parent element, but there are other elements with that class. So if for example I have an element that i get to like this:
$(document).on('click', '.countButton', function(){
var parent = $(this).parents('parentDiv');
});
How can I put that element into a selector to count it like this:
$('.parentDiv > .childDivs').length;
Is there someway to convert an element into a selector, or something that points to that element? If that makes sense..
Thanks!
So after var parent = $(this).parents('parentDiv'); you have the element you want and you just want its children with a certain class? If so
parent.children('.childDivs').length;
For direct descendants or:
parent.find('.childDivs').length;
To find elements with the 'childDivs' class at any depth with parent
Yes, you can use the parent element as context for the search:
$('.childDivs', parent).length
Which is the same as:
parent.find('.childDivs').length
Could you perhaps use:
document.querySelectorAll('.parentDiv > .childDivs').length?

Get the parent HTML element of certain type with JS

My code looks like this, in closeup:
<h2>
<span class="stuff">[<a id="someid">stuff</a>]</span> <span class="moreStuff">Another test</span>
</h2>
I've found a way to select my a element, and attach an id to it. What I need to do now is select its parent <h2> element, but not the <span> element. How can I do that (JQuery allowed)?
Edit: when I retrieve the selected <a>s, I get an array of them (there's lots of these structures on my page). When I try to write myArray[someIndex].closest("h2"), it says that the element does not have a closest() method. How would I go about this?
One ways is to use the .parents() method of jQuery, with a selector. Something like this.
$("#someid").parents("h2");
Update:
You can use the .closest() method with a selector, to only get the closest parent that match the selector.
$("#someid").closest("h2");
Update 2:
It would be a bit more work to do it with plain JavaScript. Not sure if it is the most efficient, but one way would be to select the element with document.getElementById() and then get a reference to its parent through the parentNode property. Then you would have to check if it is an h2 element, and if not, look at that elements parent node, and so on.
You could check the jQuery source and see how they have implemented the closest method.
I just needed the same thing. here a vanilla javascript variant:
function findParent(startElement, tagName) {
let currentElm = startElement;
while (currentElm != document.body) {
if (currentElm.tagName.toLowerCase() == tagName.toLowerCase()) { return currentElm; }
currentElm = currentElm.parentElement;
}
return false;
}
The <h2> is not the parent of the <a> but it is an ancestor, use .closest() to select it
$("#someid").closest("h2");
try use .parent() for get exactly double or more level up the DOM tree.
$("#someid").parent().parent();

Categories

Resources