DOM :: Query Selector in Java Script

 

query selector

querySelector() in JavaScript

querySelector takes an argument of CSS-compatible selectors and returns the first element that matches them.If your html document doesn't have a lot of content then your argument could be incredibly simple. For example, if we had the code below

Definition and Usage

The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.

Syntax

document.querySelector(CSS selectors)

Parameter Values

ParameterTypeDescription
CSS selectorsStringRequired. Specifies one or more CSS selectors to match the element. These are used to select HTML elements based on their id, classes, types, attributes, values of attributes, etc.

For multiple selectors, separate each selector with a comma. The returned element depends on which element that is first found in the document (See "More Examples").
In HTML


    <body>
        <div class="box-one" id="box">
            <h2>
                Heading
            </h2>
            <p>
                the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog
                the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog
                the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog
                the quick brown fox
            </p>
        </div>

        <script src="select.js"></script>
    </body>
   

In CSS
 
    box{
        width: 450px;
        height: 450px;
        background-color: gray;
    }
   

In JavaScript
        var txt = document.querySelector('p');
    txt.style.backgroundColor= 'red';