How to Check in JavaScript If One Element Is Contained Within Another

How to check in Javascript if one element is contained within another

Update: There's now a native way to achieve this. Node.contains(). Mentioned in comment and below answers as well.

Old answer:

Using the parentNode property should work. It's also pretty safe from a cross-browser standpoint. If the relationship is known to be one level deep, you could check it simply:

if (element2.parentNode == element1) { ... }

If the the child can be nested arbitrarily deep inside the parent, you could use a function similar to the following to test for the relationship:

function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}

How to check if there's an element inside another element with JavaScript

Replace your if condition as below and it will work as expected. It will find elements inside drinks which has class ob-menu-item__out-of-stock.

if (drink.getElementsByClassName("ob-menu-item__out-of-stock").length > 0)

Please refer this answer which says .getElementsByClassName("home")[0] should not be used. You can alternatively use .querySelectorAll() like below. Replace getElementsByClassName with querySelectorAll and pass class name with class selector (.). So document.getElementsByClassName("ob-menu-item__title")[i] will be replaced with document.querySelectorAll(".ob-menu-item__title")[i].

To find elements inside selected element you can use element.querySelectorAll which is done inside if with drink.querySelectorAll(".ob-menu-item__out-of-stock").length

for (var i = 0; i < 7; i++) {
// iterating over each drink.
var drink = document.querySelectorAll(".ob-menu-item__title")[i];
if (drink.querySelectorAll(".ob-menu-item__out-of-stock").length > 0) {
// There's out of stock text
// Do nothing and go to the next drink
} else {
//The product is available. Clik the drink and exit the loop
drink.click();
break;
}
}

Try it below.

// get all drink
var drinks = document.querySelectorAll(".ob-menu-item__title");
// iterating over each drink.
for (var i = 0; i < drinks.length; i++) {
let drink = drinks[i];

if (drink.querySelectorAll(".ob-menu-item__out-of-stock").length > 0) {
console.log('out of stock. i = ' + i);
// There's out of stock text
// Do nothing and go to the next drink
} else {
//The product is available. Clik the drink and exit the loop
console.log('In stock. i = ' + i);
drink.click();
break;
}
}
<div class='ob-menu-items__items'>
<h4 class='ob-menu-item__title'>
item0<span class='ob-menu-item__out-of-stock'> - Out of stock</span>
</h4>
<h4 class='ob-menu-item__title'>
item4<span class='ob-menu-item__out-of-stock'> - Out of stock</span>
</h4>
<h4 class='ob-menu-item__title'>
item2<span class='ob-menu-item__out-of-stock'> - Out of stock</span>
</h4>
<h4 class='ob-menu-item__title'>
item3
</h4>
<h4 class='ob-menu-item__title'>
item4
</h4>
<h4 class='ob-menu-item__title'>
item5
</h4>
<h4 class='ob-menu-item__title'>
item6
</h4>
</div>

Check if div is descendant of another

// x is the element we are checking
while (x = x.parentNode) {
if (x.id == "a") console.log("FOUND");
}

How can I check if an element is within another one in jQuery?

You could do this:

if($('#THIS_DIV','#THIS_PARENT').length == 1) {

}

By specifying a context for the search (the second argument) we are basically saying "look for an element with an ID of #THIS_DIV within an element with ID of #THIS_PARENT". This is the most succint way of doing it using jQuery.

We could also write it like this, using find, if it makes more sense to you:

if($('#THIS_PARENT').find('#THIS_DIV').length == 1) {

}

Or like this, using parents, if you want to search from the child upwards:

if($('#THIS_DIV').parents('#THIS_PARENT').length == 1) {

}

Any of these should work fine. The length bit is necessary to make sure the length of the "search" is > 0. I would of course personally recommend you go with the first one as it's the simplest.

Also, if you are referring to an element by ID it's not necessary (although of course perfectly okay) to preface the selector with the tag name. As far as speed, though, it doesn't really help as jQuery is going to use the native getElementById() internally. Using the tag name is only important when selecting by class, as div.myclass is much, much faster than .myclass if only <div> elements are going to have the particular class.

Find out if an element is a descendant of a specific element type?

You can do it recursively. The function breaks if it reaches body and not found yet.

function handleClick(event){
event.preventDefault(); event.stopImmediatePropagation(); // event.target Am I inside an anchor? const has = hasParentOfType(event.target, 'A'); console.log(has);}
function hasParentOfType(node, type) {
if (type !== 'BODY' && node.nodeName === 'BODY') return false; if (type === node.nodeName) return true; return hasParentOfType(node.parentNode, type);}
<a href="/">  <div class="AnElementInBetween">    <div class="anotherElementInBetween">      <div class="targetElement" onclick="handleClick(event)">         Am I inside an anchor element?      </div>    </div>  </div></a>

How to check if a string contains any element of a list & get the value of the element?

I think a lot easier would be to just use .find method, which returns the element when the condition in the arrow function is met (arrow function returns true).

websites = [
'google',
'youtube',
'twitter',
]

var url = window.location.href // e.g. returns www.google.com/soooomethingelse

var website = websites.find((el) => url.includes(el))
if (website) {
console.log(website) // here I want to log 'google' from 'websites'
}

Check if array contains in an object property all elements of another array in js

You can use map and every for this. With map you extract the ids into an array (keys). With every you check if for every element in array2 a condition holds.

let array1 = [
{id: 123, name: "Name of item"},
{id: 456, name: "Other name"}
]
let array2 = [123, 456]

const keys = array1.map(el => el.id)
console.log(array2.every(id => keys.includes(id)))


Related Topics



Leave a reply



Submit