How to access an element inside another HTML element with pure JavaScript

4

I would like to know how to access an element within another element through the id using pure JavaScript.

Currently I use getElementsByTagName('a') but as in my project I will have several elements of the same type, it will not be usual.

I also know getElementsByClassName('huebr') but the same is not supported in IE9.

Test environment: link

    
asked by anonymous 26.08.2014 / 20:09

2 answers

4

Selectors to jQuery:

available in the document and all elements ; function similar to jQuery, and are well supported by more modern browsers. In IE, so it is , they are available from version 8. The parameter string must contain one or more comma-separated CSS selectors, although in my most complex selector experiments (with pseudo-selectors) have failed.

// captura apenas a PRIMEIRA tag <a> da página:
var a = document.querySelector("a"); // retorna apenas o elemento encontrado (ou null)

// captura, dentro de 'a', TODOS (All) os elementos com classe "classeA" ou "classeB":
var b = a.querySelectorAll(".classeA, .classeB"); // retorna um array de filhos

Array of child elements

They are available in all elements that contain children; contains all child elements (other than pure-text nodes).

var c = b.children[0]; // exemplo de uso
Array of nodes (text / element) children

They are available in all elements, and contain all child elements (textual or not).

var d = c.childNodes[1]; // exemplo de uso
    
26.08.2014 / 20:19
4

Let's assume an element you retrieved with pure Javascript, called foo . You can get foo by methods you already know. For example:

// experimento no fonte desta página!
var foo = document.getElementsByClassName("post-text")[0];

You can use the properties children or childNodes . The number of child elements will be at childElementcount . You can use these properties as follows:

var numberOfKids = foo.childElementCount;

Remember that returning certain methods methods like getElementsByClassName can be an array. In this case each element of the array will have the properties I mentioned.

    
26.08.2014 / 20:19