How to select first parent DIV using jQuery? - javascript

var classes = $(this).attr('class').split(' '); // this gets the current element classes
var classes = $(this).parent().attr('class').split(' '); // this gets the parent classes.
The parent in the above situation is an ankor.
If I wanted to get the first parent DIV of $(this) what would the code look like?
var classes = $(this).div:parent().attr('class').split(' '); // just a quick try.
* Basically I want to get the classes of the first parent DIV of $(this).
thx

Use .closest() to traverse up the DOM tree up to the specified selector.
var classes = $(this).parent().closest('div').attr('class').split(' '); // this gets the parent classes.

Use .closest(), which gets the first ancestor element that matches the given selector 'div':
var classes = $(this).closest('div').attr('class').split(' ');
EDIT:
As #Shef noted, .closest() will return the current element if it happens to be a DIV also. To take that into account, use .parent() first:
var classes = $(this).parent().closest('div').attr('class').split(' ');

This gets parent if it is a div. Then it gets class.
var div = $(this).parent("div");
var _class = div.attr("class");

two of the best options are
$(this).parent("div:first")
$(this).parent().closest('div')
and of course you can find the class attr by
$(this).parent("div:first").attr("class")
$(this).parent().closest('div').attr("class")
and for you
$(this).parent("div:first").attr("class").split(' ')
$(this).parent().closest('div').attr("class").split(' ')

Keep it simple!
var classes = $(this).parent('div').attr('class');

Related

Javascript how to append an element to div with specific class

I have some <div>s where I want to append some data to a child div with a specific class but I'm not sure how to do that:
Here is my JS code:
let items = document.querySelectorAll(".item");
items.forEach(function (item) {
let textnode = document.createElement('p');
textnode.innerHTML = 'some text';
item.appendChild(textnode);
});
This actually works, bu it only appends the "textnode"-element to the existing elements.
When I try:
document.getElementsByClassName('left').appendChild(textnode);
It doesn't work.
Here is a JSFIDDLE
EDIT
I want to append the data to the .left element
It seems you want to append an element to .left descendant of item elements. If this is the case, you can use the querySelector instead of getElementsByClassName:
item.querySelector('.left').appendChild(textnode);
Note that above code calls the querySelector method as a member of item (instance of HTMLDivElement interface).
getElementsByClassName returns multiple elements. Class names are not unique. Therefore you first need to select an element in that list.
var textnode = document.createTextNode("Test");
var node = document.getElementsByClassName('left');
node[0].appendChild(textnode);
<div class="left"></div>
getElementsByClassName returns the array of elements. So u need to use the index for that.
let x = document.getElementsByClassName('left')
x[0].appendChild(textnode)
This is working.
I have updated the code in your fiddle. Please check out

JQuery sibling selector with multiple types

For instance if I have the following:
var siblingIcon = $(elem).siblings('i');
That looks at an element and selects all the <i> elements on the same level. How can I add to that that if siblingIcon doesn't contain anything (because no <i> elements were found, to rather look for <span> elements?
so..
var siblingIcon = $(elem).siblings('i') || $(elem).siblings('span');
You can use multiple selector there,
var siblingIcon = $(elem).siblings('i,span');
The above code will look for both i and span elements in the siblings level of the elem.
Assuming that the intention is that span should only be selected if there is no i element.
You can check the size of returned jquery object
var siblingIcon = $(elem).siblings('i').size() ? $(elem).siblings('i') : $(elem).siblings('span');
or directly length
var siblingIcon = $(elem).siblings('i').length ? $(elem).siblings('i') : $(elem).siblings('span');

Selecting a last child in javascript

I have a handle on an Un-ordered List (for my example i will call the handle Var1) and would like to be able to assign its last li to a variable. I tried Lastli = var1.lastChild the only method I figured would work but it didn't. I can't seem to find a answer to this using only Javascript not jQuery any help is appreciated.
You can select the parent element and use the lastChild property.
var container = document.getElementsByTagName("ul")[0];
var lastchild = container.lastChild;
Or you select all the items into an array and get the last item. Here is a quick example:
var items = document.querySelectorAll("li");
var lastchild = items[items.length-1];
you can select all 'li' and take the last one. Something like:
var myLi = document.getElementsByTagName('li');
var lastLi = myLi[myLi.length-1];
Lets consider an example
<ul >
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
To get the last child of the list you can simply make use of queryselector
document.querySelector('li:last-child'); //this will return Milk which is the last child of the list
document.querySelector('li:first-child') OR document.querySelector('li'); //both will give you the first child of the list
Suppose you want the n-th child for that you can use the following syntax:
document.querySelector('li:nth-child(2)'); //it will return the second child (here Tea)
If you want all the list item in the given list:
document.getElementsByTagName('li') //(Will return the whole list)here i am using tagname. It can be also applied on classname or element id
Try this: .childNodes[childNodes.length - 1]
either ulReference.children[ulReference.children.length -1] or ulReference.childNodes[ulReference.childNodes.length -1]. The difference between the two can be found here
The simplest way is to use the document.querySelector and use the :last-child to get it.
Exemple:
const list = document.querySelector("li:last-child");

Insert a div element as parent

I'm just wondering if the following is possible, lets say we have a dom element and we want to wrap this element in a div. So a div is inserted between the element and it's parent. Then the div becomes the element's new parent.
But to complicate things, elsewhere we have already done things like:
var testElement = document.getElementByID('testID')
where testID is a child of the element to be warapped in a div. So after we have done our insertion will testElement still be valid?
BTW: I'm not using jquery.
Any ideas?
Thanks,
AJ
You can use replaceChild [docs]:
// `element` is the element you want to wrap
var parent = element.parentNode;
var wrapper = document.createElement('div');
// set the wrapper as child (instead of the element)
parent.replaceChild(wrapper, element);
// set element as child of wrapper
wrapper.appendChild(element);
As long as you are not using innerHTML (which destroys and creates elements), references to existing DOM elements are not changed.
Assuming you are doing your manipulation using standard DOM methods (and not innerHTML) then — yes.
Moving elements about does not break direct references to them.
(If you were using innerHTML, then you would be destroying the contents of the element you were setting that property on and then creating new content)
You probably want something like:
var oldParent = document.getElementById('foo');
var oldChild = document.getElementById('bar');
var wrapper = document.createElement('div');
oldParent.appendChild(wrapper);
wrapper.appendChild(oldChild);
In pure JS you can try something like this...
var wrapper = document.createElement('div');
var myDiv = document.getElementById('myDiv');
wrapper.appendChild(myDiv.cloneNode(true));
myDiv.parentNode.replaceChild(wrapper, myDiv);
Here is another example, only the new element wraps around 'all' of its child elements.
You can change this as necessary to have it wrap at different ranges. There isn't a lot of commentary on this specific topic, so hopefully it will be of help to everyone!
var newChildNodes = document.body.childNodes;
var newElement = document.createElement('div');
newElement.className = 'green_gradient';
newElement.id = 'content';
for (var i = 0; i < newChildNodes.length;i++) {
newElement.appendChild(newChildNodes.item(i));
newChildNodes.item(0).parentNode.insertBefore(newElement, newChildNodes.item(i));
}
You will want to modify the 'document.body' part of the newChildNodes variable to be whatever the parent of your new element will be. In this example, I chose to insert a wrapper div. You will also want to update the element type, and the id and className values.

How to get child elements of $self, jquery is OK

$('#cont > fieldset').each(
function(index){
var $self = $(this);
// Here how to get child elements? How to write this selector?
//$('$self > div') ?? this seems does not work.
});
$self.find("div"); // return all descendant divs
or:
$self.children("div"); // return immediate child divs
depending on whether you want immediate children or any descendants.
You can even do this to get immediate child divs, but children is prettier :
$self.find(">div");
Look at the .children method in jQuery. This will get direct children of the element, e.g.:
$self.children('div') // returns divs that are direct children
You can also use the similar .find method if you need to go deeper than one level.
$self.find('div') // returns divs that are direct children, or children of children
Also, you can select using $self as the context, like:
$('div', $self) //returns all divs within $self
using children
$(this).children('div')
or
using find
$(this).find('div');
look on this post
You can use the children() method, to get all immediate children of self.
var children = $self.children();

Categories

Resources