Ways to determine if a parent element contains a child element

I am dealing with a parent element that contains a child element, but the child element is only revealed when a button is clicked.

Here is what the initial parent element looks like:

<div class="parent">
   <!--v-if-->
</div>

After the button is clicked:

<div class="parent">
   <div class="child"></div>
</div>

Now, I need to determine whether the parent element contains a child element using JavaScript. How can this be accomplished?

Answer №1

Use of el.hasChildNodes in JavaScript- This method can get the job done, however, it will also count non-element nodes.
el.children- This property only includes element nodes.

let container1 = document.getElementById("container1");
let container2 = document.getElementById("container2");
let container3 = document.getElementById("container3")

console.log('Container1 contains children - ', container1.hasChildNodes());
console.log('Container1 contains children - ', Boolean(container1.children.length));

console.log('Container2 contains children - ', container2.hasChildNodes());
console.log('Container2 contains children - ', Boolean(container2.children.length));

console.log('Container3 contains children - ', container3.hasChildNodes());
console.log('Container3 contains children - ', Boolean(container3.children.length));
<!-- container 1 -->
<div id="container1"></div>

<!-- container 2 -->
<div id="container2">
  <div id="child1"></div>
</div>

<!-- container 3 -->
<div id="container3">
  <!-- comment -->
</div>

Answer №2

At the outset, this element does contain child nodes such as two text nodes and a comment node, but it lacks any element children.

If you are curious about whether there are element children present, you can utilize firstElementChild. This will return null if no child elements exist within the element, or the first child element if they do.

const x = document.querySelector(".parent");

console.log(`Initially: ${!!x.firstElementChild}`);

// Simulate replacing the comment node with an element node
const div = document.createElement("div");
div.className = "child";
x.replaceChild(div, x.childNodes[1]);

console.log(`After Replacement:  ${!!x.firstElementChild}`);
<div class="parent">
   <!--v-if-->
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In what way could the border exceed the dimensions of the div?

<head> <meta charset="UTF-8"> <title>Document</title> <style> #Tri{ width:0px; height:0px; border-top: 50px solid yellow; border-right:50px solid red; border-bottom:50px solid green; border-left:50px solid blue; } </style&g ...

Investigating a model using various attributes

I am currently developing an app using Express and Postgres as the database, with Sequelize as the ORM. Within my database, each Post can be categorized into one of five types: 1, 2, 3, 4, or 5. My goal is to display the total number of posts for each ty ...

Creating a customized design for your jQuery UI modal dialog box using CSS

I recently had to customize the jqueryui modal dialog in order to meet the standards set by my company. Currently, I am facing a cross-browser issue with the float and width of the input labels. You can view the sample website here: http://inetwebdesign. ...

Issue with jquery_ujs: Font Awesome spinning icon animation functions properly in Chrome but not in Safari

I've integrated font-awesome-rails into my Rails project. When a user clicks the submit button on a form: The submit button should display an animated font-awesome spinner and change text to "Submitting...". The button must be disabled to prevent m ...

The value 'true' was returned for an attribute 'exact' that is not of boolean type

How can I resolve this warning? Sample Code const Main = (header, navigation) => { return ( <> <div> {navigation !== false && <Navigation />} </div> </> ) } I attempted this soluti ...

Having trouble with @here/maps-api-for-javascript in Next.js - it's not functioning

Can anyone help me understand why @here/maps-api-for-javascript is not functioning properly in my Next.js application and producing the following error message: import H from "@here/maps-api-for-javascript"; export default H; ^^^^^^ SyntaxErr ...

Tips for implementing a document ready function on a nested page within a larger full-page website

I am currently working on a website that utilizes fullpage.js, but the same principle applies to all single-page websites. I am trying to figure out how to implement the $(document).ready() function on a 'nested' page within the site. Since every ...

Tips for adjusting the font size according to the varying number of characters entered

I am currently facing a challenge with adjusting the font size based on the dynamic number of characters. For example, I have a set of characters with a font-size of 40px, and as more characters are added, the font size should decrease to fit within the av ...

HTML/PHP rookie blunder: An invalid argument was passed to the implode() function ~~

Seeking assistance on html, mysql, and php as a newcomer in these areas. In my html code, I have set up three checkboxes named "userTime[]". <label for = "day">Day Time (12:00~16:00)</label> <input id = "day" type = &quo ...

In what way can the result of the code displayed be considered as truthful?

this.someService.findDevices() .subscribe((segments) => { this.segments = Array.from(segments.segments); this.packs.forEach((pack) => { pack.segments = Array.from(segments.segments); pack. ...

Verify the checkboxes in one row

How can I create a table row that will automatically generate data from SQL and bind it using backend code? Is there a way to check if the user has clicked on it using JavaScript? The row is created as shown below: <tr> <td align="right" cl ...

Mastering the art of gracefully transitioning to a fallback option when CSS grid

When it comes to creating a simple grid of squares (3x3 at most, filling in top to bottom left to right), I have encountered challenges with both flexbox and grid. The DOM structure required for each method seems incompatible or too complex to support both ...

Use yarn to install both devDependencies and dependencies simultaneously

Can yarn be used to install devDependencies and dependencies simultaneously? For instance, if I need to install react as a dependency and webpack as a dev dependency. Typically, I would have to execute two separate commands like shown below: yarn add reac ...

How can I attach an event listener to each row in a table that is dynamically generated?

I am currently working on a table that is being populated using data from a JSON file. The number of entries in the JSON file can vary, resulting in different lengths for the table rows. Each row includes a bootstrap dropdown button with links for actions ...

Remove the content located beside an input element

Seeking assistance for a straightforward query: Snippet of code: <span> <input id="elemento_20_1" name="elemento_20_1" class="elemento text" size="2" maxlength="2" value="" type="text"> / <label for="elemento_20_1">DD</label> < ...

Why is it important to incorporate the CSS property background-repeat: repeat; into our code?

It is believed that if you don't expressly mention the background-repeat in CSS styling, browsers will automatically set it as background-repeat: repeat. With this default behavior in place, one might wonder why there is even a need for a separate ba ...

Utilizing the Mouse Hover feature to target various <div id> elements within a single Vue.js function

I have created two div IDs in an HTML file where I have specified the mouseover property. <div id="app"> <img class="img-responsive img-full" v-bind:src="imgData" @mouseover="imgData = imgData_1"> </div> <div id="app1"> <img cl ...

Creating a JavaScript object using a provided JSON string

Having a large JSON data that needs to be parsed in order to extract objects from the given JSON string. The top part of the data has been included here. Initial attempts to parse it using the code snippet below resulted in an error: let obj = JSON.parse(t ...

The gridOptions.$gridScope.columns in ng-grid is modified two times when hiding or showing columns

Question: Why does the $scope.$watch function get called twice when I manually hide/show a column but only once when I reorder/sort columns in ng-grid? When I specifically target a single column with the watch function, it is only called once. I suspect ...

Chakra UI Not Displaying Proper Responsiveness on the User Interface

I recently integrated Chakra UI for styling a project on Next.js, and while most components are functioning properly, I am facing challenges with implementing responsive layouts. The styles do not seem to adapt when the screen size is reduced. Here's ...