Alternative way to search for child elements within an element without the use of jQuery

I am in the process of creating a universal set of functions to verify the existence of children with specific attributes within a particular element. Unfortunately, I do not have access to jQuery for this task.

Here is an example function call:

has_child_with_id(element, 'obj123');

I am striving to ensure compatibility across various browsers and plan to have distinct functions for finding elements by name, id, class, and more.

Although I am new to the JavaScript module pattern, I am considering if the following approach would be suitable:

var myfunctions = (function() {
    var public_interface = {
        // NAMED FUNCTION
        has_child_with_id: function(el, n) {
            return public_interface.has_child_with_('Id', el, n);
        },
        // GENERIC FUNCTION
        has_child_with_: function(type, el, n) {
            // Option 1 (querySelectorAll)
            return typeof el['querySelectorAll'] === 'function' && el['querySelectorAll']('['+type+'="'+n+'"]').length > 0

            // Option 2 (get a bunch of elements, doesn't work on forms)
            || typeof el['getElementsBy'+type] === 'function' && el['getElementsBy'+type](n).length > 0

            // Option 3 (get a single element)
            || typeof el['getElementBy'+type] === 'function' && typeof el['getElementBy'+type](n) !== 'undefined'

            // Option 4 (Manually loop through elements)
            || (function(children, n) {
                for (var i=0;i<children.length;i++) {
                    if (children[i].hasOwnProperty(type) && children[i][type] == n)
                        return true;
                }
                })(el.getElementsByTagName('*', n));
        }
    };

    return public_interface;
})();

alert(myfunctions.has_child_with_id(document, 'myid'));

Answer №1

Using document.querySelector is a great way to find elements within your HTML document. It works well with IE8+ and even supports CSS3 selectors in IE9. Instead of searching the whole document, you can specify the element to search within.

This method allows you to find the first element that matches a class, ID, or data attribute.

var elem = document.querySelector('#some-element');
var firstMatch = elem.querySelector('.sample-class');

If you need to find all elements that match a certain class, ID, or data attribute, you can use:

var elem = document.querySelector('#some-element');
var allMatches = elem.querySelectorAll('.sample-class');

Make sure to pay attention to the variables firstMatch and allMatches, as they hold the elements you're interested in.

You also have the option to search by ID, data attribute, or any other valid CSS selector:

elem.querySelectorAll('[data-something]'); // Finds elements with a specific data attribute
elem.querySelectorAll('input[type="checkbox"]'); // Retrieves all checkboxes on the page

The querySelectorAll function will give you an array of nodes that you can iterate through efficiently.

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

How to Use a Discord Bot to Send a Message (Step-by-Step Guide)

I am looking for a simple way to send a message using my discord bot, but everything I have found online seems too complex for me to understand and implement. require("dotenv").config(); //to start process from .env file const { Client, GatewayIn ...

Modifying the value of an animated status bar using the same class but different section

I need the status bars to work individually for each one. It would be great if the buttons also worked accordingly. I have been trying to access the value of "data-bar" without success (the script is able to process the "data-max"). However, the script see ...

Guide on implementing Regular Expressions in Directives for validation in Angular 8

Managing 8 different angular applications poses its unique challenges. In one of the applications, there is a directive specifically designed for validating YouTube and Vimeo URLs using regular expressions. Unfortunately, once the RegExp is declared, ther ...

Prevent sticky div from overlapping with footer

I currently have a social link menu that is fixed to the left side of my page, structured like this: <footer id="colophon"></footer> <div> <nav> <ul id="social"> <li>Link1</li> ...

Node js server for world's warm greetings

I have been attempting to utilize Node.js for hosting a web server on a dedicated PC, but unfortunately I am unable to access it from anywhere outside of my local network. After researching online, the general consensus is that all I need to do is enter t ...

The current Webpack configuration for production fails to account for importing CSS files

I am struggling to figure out how to properly load a static site that is not located in the root folder: let HWPTest = new HtmlWebpackPlugin({ template: __dirname + "/src/artists/test.html", filename: 'artists/test.html', favicon: &apos ...

Incorporating dynamic numerical values into image names within a Vue JS application

I have linked an image with the following code <img title="head" :src="availableParts.heads[selectNextHeadIndex].src"/> This image is called from a JSON file: { id: 1, description: 'A robot head with an ...

Display a loading spinner on the browser while the form is being submitted

My current project involves using AJAX to retrieve data and populate a form. The data being fetched is quite large, resulting in a delay as it is fetched from the database and filled into the form fields. During this process, I display a loading icon to in ...

Utilizing Fullcalendar Qtip to display information on mouseover rather than utilizing the eventRender

I have a challenge with integrating Qtip to the eventMousever event instead of the eventRender event in fullcalendar. The main reason for this adjustment is due to the server hosting the data being located in another country, resulting in significant late ...

Is the controller of a nested view in Angular UI router automatically considered a child of the parent view's controller?

My UI-Router setup includes a main view for products and two nested states below it. I want each nested view to have its own controller while also inheriting some basic information from the parent controller (productsCtrl). However, when attempting to acce ...

Fetching the second item within an object using JavaScript

I am trying to retrieve the data from the last month of an API, but I want to avoid hard-coding the date like this: const data = [data.data['Monthly Time Series']['2021-11-30']]. I need a way to dynamically access the 2nd object without ...

Angular Universal causing issues with updating the DOM component

@Component({ selector: 'mh-feature-popup', template: ` <div class="full"> <div> <div class="container-fluid" [@featurepop]="state"> <div class="row"> <div class="col-xs-12 col-md-4 col-md-offse ...

Moving files by dragging and dropping rather than deleting them

I have successfully implemented a feature using JavaScript to drag and drop multiple files, followed by displaying those images. The code below is fully functional without any errors. Need help with: I am now looking to add the ability to remove these ima ...

The scroll animation feature was not functioning properly in Next.js, however, it was working flawlessly in create react app

I recently transitioned a small project from Create React App (CRA) to Next.js. Everything is working as expected except for the scroll animations in Next.js, which are not functioning properly. There are no errors thrown; the animations simply do not occ ...

What is the best way to pass multiple variables to a PHP file with AJAX using a GET request?

Can you help me figure out how to send both an I.D. value and a name value to a php file using ajax? Currently, I am successfully sending just the I.D. variable, however, when I attempt to add the name variable, the function stops working. The code that w ...

applying a timeout for the .on(load) event

My goal is to dynamically load images using .on('load') in the script below: .on('load', function() { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { alert('broken i ...

React/Next Component Changes State and Clears it in useEffect

Currently, I am faced with an issue while attempting to fetch data from an API. The problem arises during the rendering process since the useEffect function is being called multiple times. Surprisingly, everything works perfectly fine during the initial pa ...

The provisional headers provided by the local passport authentication strategy offer an added layer

When I send a POST request from my frontend with a username and password object, here is the code: const login = data => ( axios.post('http://localhost:3000/v1/user/login', data) .then(response => response.data) .catch((err) => ...

The error message "No native build was found for M2 MacBook" appeared while using npm with Node

I encountered this issue while working on my M2 MacBook, which ran smoothly on my older Intel MacBook. Any insights on what might be causing the problem? Using bun, but even running npm run dev (node 18) results in the same error. The same error has also ...

What is the process for creating a custom Vue 3 element with incorporating styles for child components?

After experimenting with Vue's defineCustomElement() to develop a custom element, I encountered an issue where the child component styles were not being included in the shadow root for some unknown reason. To address this problem, I took a different ...