Table of Contents
Understand the closest() method
Alternatives
Summarize
Home Web Front-end JS Tutorial Get the text tag of the parent Option Group

Get the text tag of the parent Option Group

Sep 01, 2025 am 07:21 AM

Get the text tag of the parent Option Group

This article describes how to use JavaScript to obtain text tags for the parent tag of the selected

Understand the closest() method

In JavaScript, the closest() method is used to find the first ancestor element that matches the specified selector. In the above question, the code uses opt.closest('optgroup').attr('label') to get the label attribute of the parent . However, since the tag, closest('optgroup') finds "Sub" instead of "Main".

Problems with nesting

Nested tags are not always properly supported in HTML and can cause browser rendering issues. Therefore, it is recommended to avoid using nested tags.

Alternatives

If you need to achieve grouping-like effects, you can consider the following alternatives:

  1. Flat structure data properties: Remove the tag and use the data properties to identify the group to which each

     <select id="categoryg">
        <option value="46" data-group="Main">Test</option>
        <option value="47" data-group="Main">Test2</option>
        <option value="48" data-group="Main">Test3</option>
    </select>

    You can then use JavaScript to get the data-group property of the selected

     $('select').change(function () {
        var opt = $(this).find(':selected');
        var group = opt.data('group');
    
        console.log(group); // Main
    });
  2. Manually build options with JavaScript: Remove the tag completely and generate the

     const data = [
      { group: 'Main', value: '46', text: 'Test' },
      { group: 'Main', value: '47', text: 'Test2' },
      { group: 'Main', value: '48', text: 'Test3' },
    ];
    
    const select = document.getElementById('categoryg');
    
    data.forEach(item => {
      const option = document.createElement('option');
      option.value = item.value;
      option.textContent = item.text;
      option.dataset.group = item.group;
      select.appendChild(option);
    });
    
    $('select').change(function () {
        var opt = $(this).find(':selected');
        var group = opt.data('group');
    
        console.log(group); // Main
    });
  3. Traversing the DOM tree: If you really need to get the tag of "Main" and make sure that the HTML structure remains unchanged, you can use the parents() or parent() method to traverse the DOM tree upward until the target tag is found. However, this method relies on a specific HTML structure and is less maintainable.

     $('select').change(function () {
        var opt = $(this).find(':selected');
        var og = opt.closest('optgroup').parent().closest('optgroup').attr('label');
    
        console.log(og); // Main
    });

    Note: This method relies on a fixed HTML structure, and the code will fail if the HTML structure changes.

Summarize

Getting text tags for parent tags requires understanding how the closest() method works and pay attention to the problems that may arise from nesting tags. It is recommended to use flat structures and data properties, or use JavaScript dynamic build options for more flexible and maintainable grouping effects. If you must use nested structures, use DOM traversal with caution and ensure the robustness of your code.

The above is the detailed content of Get the text tag of the parent Option Group. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vercel SPA routing and resource loading: Solve deep URL access issues Vercel SPA routing and resource loading: Solve deep URL access issues Aug 13, 2025 am 10:18 AM

This article aims to solve the problem of deep URL refresh or direct access causing page resource loading failure when deploying single page applications (SPAs) on Vercel. The core is to understand the difference between Vercel's routing rewriting mechanism and browser parsing relative paths. By configuring vercel.json to redirect all paths to index.html, and correct the reference method of static resources in HTML, change the relative path to absolute path, ensuring that the application can correctly load all resources under any URL.

Vercel Single Page Application (SPA) Deployment Guide: Solving Deep URL Asset Loading Issues Vercel Single Page Application (SPA) Deployment Guide: Solving Deep URL Asset Loading Issues Aug 13, 2025 pm 01:03 PM

This tutorial aims to solve the problem of loading assets (CSS, JS, images, etc.) when accessing multi-level URLs (such as /projects/home) when deploying single page applications (SPAs) on Vercel. The core lies in understanding the difference between Vercel's routing rewriting mechanism and relative/absolute paths in HTML. By correctly configuring vercel.json, ensure that all non-file requests are redirected to index.html and correcting asset references in HTML as absolute paths, thereby achieving stable operation of SPA at any depth URL.

Qwik: A Resumable Framework for Instant-Loading Web Apps Qwik: A Resumable Framework for Instant-Loading Web Apps Aug 15, 2025 am 08:25 AM

Qwikachievesinstantloadingbydefaultthroughresumability,nothydration:1)TheserverrendersHTMLwithserializedstateandpre-mappedeventlisteners;2)Norehydrationisneeded,enablingimmediateinteractivity;3)JavaScriptloadson-demand,onlywhenuserinteractionoccurs;4

js add element to start of array js add element to start of array Aug 14, 2025 am 11:51 AM

In JavaScript, the most common method to add elements to the beginning of an array is to use the unshift() method; 1. Using unshift() will directly modify the original array, you can add one or more elements to return the new length of the added array; 2. If you do not want to modify the original array, it is recommended to use the extension operator (such as [newElement,...arr]) to create a new array; 3. You can also use the concat() method to combine the new element array with the original number, return the new array without changing the original array; in summary, use unshift() when modifying the original array, and recommend the extension operator when keeping the original array unchanged.

How to lazy load images with JavaScript How to lazy load images with JavaScript Aug 14, 2025 pm 06:43 PM

Usetheloading="lazy"attributefornativelazyloadinginmodernbrowserswithoutJavaScript.2.Formorecontrolorolderbrowsersupport,implementlazyloadingwiththeIntersectionObserverAPIbysettingdata-srcfortheactualimageURLandusingaplaceholderinsrc.3.Obse

In-depth analysis of common vulnerabilities and improvement strategies for JavaScript XSS defense functions In-depth analysis of common vulnerabilities and improvement strategies for JavaScript XSS defense functions Aug 14, 2025 pm 10:06 PM

This article explores in-depth security vulnerabilities in custom JavaScript XSS defense functions, especially incomplete character escape and easy bypass to keyword-based filtering. By analyzing an example function, it reveals the risks of unprocessed keyword characters such as quotes and backquotes, and how code obfuscation techniques circumvent simple keyword detection. The article emphasizes the importance of context-sensitive escape and recommends the adoption of mature libraries and multi-layer defense strategies to build more robust security protection.

How to access and modify HTML elements using the DOM in JavaScript How to access and modify HTML elements using the DOM in JavaScript Aug 16, 2025 am 11:25 AM

ToaccessandmodifyHTMLelementsusingJavaScript,firstselecttheelementusingmethodslikedocument.getElementById,document.querySelector,ordocument.querySelectorAll,thenalteritscontent,attributes,orstyles;forexample,useelement.textContentforsafetextupdates,e

Optimize event handling of dynamic external link jumps in jQuery pop-up window Optimize event handling of dynamic external link jumps in jQuery pop-up window Sep 01, 2025 am 11:48 AM

This article aims to solve the problem of redirecting the external link redirect button in jQuery pop-up window causing jump errors. When a user clicks multiple external links in succession, the jump button in the pop-up may always point to the first clicked link. The core solution is to use the off('click') method to undo the old event handler before each binding of a new event, ensuring that the jump behavior always points to the latest target URL, thus achieving accurate and controllable link redirection.

See all articles