seriousy? i cant find anything on google is there like a page regarding this kind of stuff?

Dani AI

Generated

Short, practical alternatives to this and document.getElementById — for folks who prefer plain JavaScript (and for who said jQuery feels hard). already pointed out selector-based approaches; below are other built-in, browser-friendly ways to grab elements and a quick note on handling events without relying on this.

Common DOM accessors you can use right away:

var el = document.getElementById('myId');
var items = document.getElementsByClassName('item');   // live HTMLCollection
var divs = document.getElementsByTagName('div');
var radios = document.getElementsByName('choice');
var user = document.forms['login'].elements['username'];

Event handlers and the this problem: prefer addEventListener and use the event object to know exactly which element fired the event. event.currentTarget is the element the handler is attached to; event.target is the actual sub-element clicked. Avoid arrow functions when you rely on this, because arrows do not bind their own this.

document.getElementById('btn').addEventListener('click', function (e) {
  console.log(this);            // handler's bound element
  console.log(e.currentTarget); // same as this
  console.log(e.target);        // actual element clicked
});

A few useful tips: getElementsByClassName and getElementsByTagName return live collections that update as the DOM changes; querySelectorAll (selector-based) returns a static list — pick the behavior you want. Modern browsers support these methods; if you must support very old browsers (IE8-era) you’ll need fallbacks or tiny polyfills. For quick documentation, see the MDN pages on selection and event binding, for example getElementsByClassName and addEventListener.

Recommended Answers

All 6 Replies

in Firefox you can use the built-in document.querySelector and document.querySelectorAll which use CSS selectors to find DOM elements. Similarly using the jQuery library you can do things like

$('#somediv > p') // returns all p tags that are children of a div with the ID of somediv

interesting but only for users who r using firefox?

Well that only applied to the document.querySelector part. jQuery supports pretty much every modern browser. http://jquery.com

yeah i dont like jquery. too comlicated

jQuery is actually one of the simplest Javascript libraries around. It's important to know at least a one be it jQuery or Prototype or Mootools, etc. The reason those libraries exist is to save you time and effort.

well i dont understand the javascript that well yet so jquery is hard as well

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.