Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript get child element

Why this does not work in firefox i try to select the category and then make subcategory visible.

<script type="text/javascript">     function show_sub(cat) {       var cat = document.getElementById("cat");       var sub = cat.getElementsByName("sub");       sub[0].style.display='inline';  }  </script> 

-

<ul>     <li id="cat" onclick="show_sub(this)">         Top 1         <ul style="display:none" name="sub">             <li>Sub 1</li>             <li>Sub 2</li>             <li>Sub 3</li>         </ul>     </li>     <li>Top 2</li>     <li>Top 3</li>     <li>Top 4</li> </ul> 

EDIT Answer is:

<script type="text/javascript">    function show_sub(cat) {       cat.getElementsByTagName("ul")[0].style.display = (cat.getElementsByTagName("ul")[0].style.display == "none") ? "inline" : "none";    } </script> 
like image 616
redacted Avatar asked May 12 '12 22:05

redacted


People also ask

How to get the child nodes of an element in JavaScript?

JavaScript DOM — Get the children of an element August 07, 2020 Atta To get all child nodes of an element, you can use the childNodes property. This property returns a collection of a node's child nodes, as a NodeList object.

How to get the child element of a Div in JavaScript?

Now I will just show you how to get the child element of our parent div. To get all the child nodes of our parent nodes (You can think it about the parent ID), below is our JavaScript code: var parent = document.getElementById('parentDiv'); var childs = parent.childNodes;

How do I get the child elements of a specified element?

To get a live NodeList of child elements of a specified element, you use the childNodes property: The childNodes property returns all child elements with any node type. To get the child element with only the element node type, you use the children property: The following example selects all child elements of the element with the Id main:

What is the children property in JavaScript?

The children property extracts the element type node mentioning some other functions. Altogether, it will count the length of the total child elements under a parent. Each iteration will also have the detail for each element. Here, the returned object is an HTMLCollection, and it only contains the element nodes’ specifications.


1 Answers

ULs don't have a name attribute, but you can reference the ul by tag name.

Try replacing line 3 in your script with this:

var sub = cat.getElementsByTagName("UL"); 
like image 65
mkruzil Avatar answered Sep 23 '22 21:09

mkruzil