How to access an element within another HTML element with pure Javascript

Asked

Viewed 2,689 times

5

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

Currently 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 the getElementsByClassName('huebr') but the same is not supported in IE9.

Testing environment: http://jsfiddle.net/douglas1551/mgy6z0uo/

2 answers

5


Selectors a la jQuery:

Are available on Document and in all elements; work similarly to jQuery, and are well supported by the most modern browsers. In IE, by the way, are available from version 8. The parameter string must contain one or more comma-separated CSS selectors, although in my more complex selector experiments (with pseudo-selectors) 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 child elements; they contain all child elements (other than plain text).

var c = b.children[0]; // exemplo de uso

Node array (text/element) children

Are available in all elements, and contains all child elements (textual or not).

var d = c.childNodes[1]; // exemplo de uso
  • Thank you very much, it will be extremely useful the mentioned querySelector. Valew!

4

Let’s assume an element you recovered with pure Javascript, called foo. You can get foo by the 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 amount of child elements will be in childElementcount. You can use these properties as follows:

var numberOfKids = foo.childElementCount;

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

  • 1

    Thank you for the reply Renan, but IE9 does not support getElementsByClassName in my case I will really use getelementsbytagname('a')[0] I have simple access to the elements. Valew

Browser other questions tagged

You are not signed in. Login or sign up in order to post.