Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript selectors

How does one select DOM elements in javascript?
Like for example:

<div class="des">
    <h1>Test</h1>
        <div class="desleft">
          <p>Lorem Ipsum.</p>
        </div>
        <div class="Right">
           <button>Test</button>
        </div>
</div>

Now how do i select h1? This is just a part of a bigger Page, so cannot use getElementsByTagName(), since others might get selected. Also since there might be other h1's in the document later, i cannot attach the index(body's) to above.

Is there a simple way to select, say <h1> tag which is under the classname of desleft? I cannot use jQuery or any other libraries.

like image 779
Aaditi Sharma Avatar asked Sep 08 '11 19:09

Aaditi Sharma


People also ask

What are JavaScript selectors?

Selectors are used to "find" (select) HTML elements based on their tag name, id, classes, types, attributes, values of attributes and much more.

How many selectors are there in JavaScript?

DOM Selectors, as the name suggests is used to select HTML elements within a document using JavaScript. There are 5 ways in which you can select elements in a DOM using selectors.

What is CSS selector in JavaScript?

A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them.


1 Answers

You can use this to get to your H1:

var des = document.getElementsByClassName('des')
var fc = des[0].getElementsByTagName('h1')
alert(fc[0].innerHTML)
like image 190
Diodeus - James MacFarlane Avatar answered Oct 08 '22 08:10

Diodeus - James MacFarlane