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

Is there a way for me to access a user control property directly from the client side?

I'm in the process of developing several user controls that will be derived from my base class, BaseControl, which is a subclass of UserControl. The BaseControl class contains important features that I will need to utilize, including a string property ...

The $(document).ready function may not be compatible with Internet Explorer

I have a page with two links - one for registering and one for logging in. Currently, the register link is the most important. When clicked, it loads a .tpl file using jQuery's load function. Within this tpl file, I include a new JavaScript file usin ...

React encountered an issue: each child element within a list must be assigned a unique "key" prop

I am feeling a bit puzzled as to why I keep getting the error message: child in a list should have a unique "key" prop. In my SearchFilterCategory component, I have made sure to add a key for each list item using a unique id. Can you help me figu ...

Control the frequency of server requests within a set limit

Currently, I am utilizing the request-sync library to fetch data from a specific site's API. This is how my code looks: let req = request('GET', LINK, { 'headers': { 'Accept' ...

Leveraging Forms for Entering Google Maps Information

Recently, I've been working on an app that aims to generate a custom map based on user input from a form. If you'd like to test the functionality yourself, head over to this page. After filling out all required fields and hitting "Submit", the g ...

Integrate Ruby parameter into JavaScript in Rails

I have a div that I want to turn into a link to another page. Typically, we achieve this using link_to link. <% for item in @items %> <%= link_to "Item", item %> # -> or <%= link_to(item) %> <% end %> However, I need the ent ...

How can I send and retrieve multiple variables in a URL using WordPress?

There seems to be an issue where I can only retrieve the first variable, specifically "product_category," from the URL http://localhost/coffeesite/?product_category=coffee&brand=bourbon. When I output JavaScript to confirm that the variables are set, ...

Utilize the UseQuery graphql function in conjunction with the useState hook within useEffect, allowing for the execution of an additional useEffect to update additional state

In my NextJS project, I am utilizing Apollo for graphQL queries and encountering an issue with the stateData.allProducts section. Despite setting the state in the useEffect and including data as a dependency in the array, the error claims it is null when d ...

<a href> click here to append a new query parameter to the existing ones

Is there a way to create a link that will add a query parameter to the current URL instead of replacing all existing ones? Here's what I'm looking for: If the current URL in the browser is example.com/index.html, clicking on it should lead to ...

Using TypeScript to Verify the Existence of Words in a String

Is there a way in typescript to find specific words within a given string? For example: If we have a list: ['Mr', 'Mrs', 'FM.', 'Sir'] and a string named 'Sir FM. Sam Manekshaw'. The words 'Sir' ...

Ways to determine if an object contains an array

Looking at the following data structure: [ 13, { a: [ [ '2988.30000', '0.19000000', '1549294216.653040' ] ] }, { b: [ [ '2988.30000', '0.00000000', '1549294216.653774&a ...

The Node.js Express undefined callback function is causing issues

I'm currently working on a personal project and I don't have much experience with nodeJS. My goal is to retrieve remote JSON data, generate statistics based on that data, and display it. However, I am encountering some issues with the callback fu ...

Utilizing custom form fields with JavaScript in Symfony2

Here is my form field template: {% block test_question_widget %} {% spaceless %} <div {{ block('widget_container_attributes') }}> {% set type = type|default('hidden') %} <input type="{{ typ ...

React-select allows for multiple selections within a component when the onChange function

I am currently utilizing react-select. Per the official documentation, it recommends using 'isMulti' to select more than one option. Below is the custom component that I have created. import React from 'react'; import { Form } from &ap ...

Experiencing a problem with a loop in iMacros/JS?

I have an iMacros/JS script for Facebook that logs into a FB account from a CSV file, then it has a second loop j which sends 20 friend requests from each account. The issue arises when switching accounts and encountering a popup message requiring phone n ...

An easy guide to accessing a data attribute using the .on function!

In my quest to retrieve the HTML data attribute labeled productId, I attempted the following code snippet: $('body').on("click", '.myButton', function () { var productId = (this).dataset.productId; }); I have multiple but ...

Tips on resolving JavaScript's failure to adjust to the latest HTML inputs

I'm working on a homepage where users can choose their preferred search engine. The issue I'm facing is that even if they switch between search engines, the result remains the same. I've experimented with if-then statements, but the selecti ...

Avoiding Scroll Reset on Browser Navigation with Delayed Transition

I've recently implemented a delay in my router configuration on my website. However, I've noticed that when I try to navigate using the browser's back and forward buttons, it first jumps to the top of the page because of the delay set with { ...

What is another option for toggling in jQuery?

After deprecating the toggle method, I found a new way to toggle div: $("#syndicates_showmore").on("click", function () { if (!clicked) { $('#syndicates').fadeTo('slow', 0.3, function () { $(this).css( ...

Step-by-step guide on accessing and displaying a disc file within a webix application

I am a beginner in webix development and struggling to find documentation or help for my current issue. Within my webix application, I am trying to create a button (let's call it 'View Report') that when clicked will open a file from my loc ...