Joel
Joel

Reputation: 460

How to access specific elements with getElementByClassName

I want to access the input elements where the type is "checkbox" and ignore the input tags that has the type "text".

When I use the code bellow I get an error message:

TypeError: outerField.getElementsByTagName is not a function

Dos anyone have a suggestion on how to solve this?

The javascript:

 outerField = document.getElementsByClassName("outerField");
 checkboxes = outerField.getElementsByTagName("input");

The html markup:

 <section id="images">
  <div class="outerField">
    <input type="checkbox">
        <img src="lorem.jpg">
    <div class="innerField">
         <input type="text" value ="">
    </div> 
  </div> 

Upvotes: 0

Views: 307

Answers (5)

KooiInc
KooiInc

Reputation: 122906

document.querySelector[All] (see MDN) makes your life a lot easier:

var cbxs = document.querySelectorAll('.outerField > input[type=checkbox]');
// demo: show length of cbxs within 'div.outerField')
document.querySelector('.outerField')
  .appendChild(document.createTextNode('length of checkboxes ' + cbxs.length));
<section id="images">
  <div class="outerField">
    <input type="checkbox">
        <img src="lorem.jpg">
    <div class="innerField">
         <input type="text" value ="">
    </div> 
  </div>

Upvotes: 1

Zee
Zee

Reputation: 8488

document.getElementByClassName("outerField");

should be

document.getElementsByClassName("outerField"); //s was missing:typo

and outerField is an array , use it like

outerField[0].getElementsByTagName("input");

Upvotes: 1

rajmeet singh
rajmeet singh

Reputation: 92

method name is getElementsByClassName not getElementByClassName. You will get a collection of elements in return

Upvotes: 1

Pascal Ockert
Pascal Ockert

Reputation: 984

You can use querySelectorAll which uses a CSS like syntax to filter for the class and the checkboxes:

document.querySelectorAll('.outerField input[type=checkbox]')

Upvotes: 2

OddDev
OddDev

Reputation: 3734

You have a typo. The function is called "getElementsByClassName" not "getElementByClassName" (notice the "s" in "Elements").

https://developer.mozilla.org/de/docs/Web/API/Document/getElementsByClassName

You get back every element which has the class "outerField" not a single element. You have to access a particular element in this HTMLCollection.

In your example this should work:

 outerField = document.getElementsByClassName("outerField");
 checkboxes = outerField.item(0).getElementsByTagName("input");

Upvotes: 2

Related Questions