Hello programmers! Welcome back to Progrramers – Web Development Tutorials. In this JavaScript tutorial, we will explore the methods to target the HTML Elements with CSS Selectors & Combinators using JavaScript. But before we step forward, allow me to inform you that you must know about the CSS Selectors & Combinators. If you’ve no idea about CSS Selectors & Combinators then please write it up in the comment section, I’ll post a separate article for that.

So, Let’s Start! We all know the fact that these days every single website is developed using multiple programming & scripting languages like PHP, JavaScript, CSS, etc. JavaScript is the most popular scripting language used on websites across the globe, therefore, it become essential to know the advanced uses of JavaScript.

We always become terrified of the target HTML Elements using JavaScript. Therefore, here we will try to present every content in a very simple way so that everything become crystal clear.

What is the CSS Selector?

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.

CSS Syntax

 

Code Copied

selector{property:value}

 

Code Copied

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        h1{color:#ff0000;}
    </style>
</head>

<body>
    <h1>This is heading</h1>
    <p>This is an example paragraph.</p>
</body>

</html>
Try Yourself

Explanation

In the above example, h1 is the selector of H1 heading element. With this selector, you can target all the <h1> elements on the webpage.

You can also read: JavaScript Tutorial : 5+ Methods To Target HTML Element In JavaScript, HTML JavaScript DOM

What is the CSS Combinator?

A CSS Combinator is something that describes the relation between HTML Element and the Selector. CSS Combinator is used to target one or more desired element(s) among the many elements. Just like the below example:

  • descendant selector (space)
  • child selector (>)
  • adjacent sibling selector (+)
  • general sibling selector (~)

 

Code Copied

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        h1~p{color:#ff0000;}
    </style>
</head>

<body>
    <h1>This is heading</h1>
    <p>This is an example paragraph.</p>
</body>
</html>
Try Yourself

 

Explanation

In the above example, you can see the adjacent paragraph of h1 is colored with ‘Red’ but which paragraph is before H1 tag is not styled with red color. This is done with the help of combinators.

 

How CSS Selectors and Combinators can be used in JavaScript?

To use CSS selectors &amp; combinators in JavaScript we have to use method which is querySelector() or querySelecrorAll(). Both methods are the part of document class of core JavaScript where CSS Selector & Combinators are used as parameters. You can see in the below example:

 

Code Copied

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        h1~p{color:#ff0000;}
    </style>
</head>

<body>
    <span>My Text</span>
    <script>
        document.querySelector("span").innerHTML="Hello Programmers!";
    </script>
</body>

</html>
Try Yourself

Explanation

When you run the code in Try Your Self you can find “My Text” inside <span> element is changed with “Hello Programmers!” text. Here what is going on that the querySelector() method targets the <span> element and changes it’s inner HTML content by using innerHTML property. The innerHTML property sets or returns the HTML content inside of an element.

 

You can also read: JavaScript Tutorial: What Are Ways To Get Output Data In JavaScript?

 

What is the difference between qureySelector() and qureySelectorAll() ?

Before we move ahead it might be possible that a question will be raised in your mind what’s the difference between querySelector() and querySelectorAll()? The answer is very simple querySelector() is a method that is used to target the only first HTML element occupied in a webpage by using CSS Selectors &amp; Combinators but querySelectorAll() targets and returns all the similar kinds of elements by using the same CSS Selectors &amp; Combinators.

How to target HTML element with querySelector() method?

This is very simple likewise in the previous article we have done with document.getElementByID(“element-ID-Attribute”). Here is only the difference that whenever we target by document.getElementByID() method we use Id attribute string inside the parenthesis as parameter but here in querySelector(“#element-ID-Attribute”) we can also use elements Id attribute started with ‘#’ and if we use the class of element then we must be started with ‘.’ like in CSS. . Element's tag name can be also used. You can also check the below examples:

 

Code Copied

    <script>
        document.querySelector("p").style.color="red";
    </script>
Try Yourself

Explanation

The above example shows that querySelector(“#demo”) method targeted only the first element of the webpage and add a style attribute with CSS Color property & red color value there for only the first paragraph text turned red.

 

Code Copied

    <script>
        document.querySelectorAll("p").forEach(e => {
            e.style.color="red";
        });
    </script>
 
Try Yourself

Explanation

In the above example, you can see all the paragraph's colors turn into ‘Red’ because we have used to add style attribute property with the red color value to all paragraphs by using foreach loop.

The querySelectorAll() target and returns a node list of all the similar kinds of elements on the webpage this is why we have used foreach loop in this case.

Keep going with our upcoming articles on JavaScript where we will discuss foreach loop.

This is why it becomes easy to target the HTML element with CSS Selectors & Combinators. Look at the more examples given below and try them yourself.

How to use ID & Class Attributes

ID and Class are attributes of an element and both can be used with any HTML element. ID refers to the identity of any HTML element occupied on a loaded document on a webpage. Id of an element on a loaded webpage must unique. For e.g., <h2 id=”demo”></h2> where demo is a unique id reference of <h2> element and after it no HTML element id  can be referred as ‘demo’.

Although using it twice or more will not through any error until any kind of coding conflict occurs but it is against the system's nature. An Id attribute of an HTML element can have a single id.

Class attribute refers an HTML element as part of a class. For e.g., <h2 class=”demo demo1”></h2>, <h2 class=”demo demo2”></h2>, <h3 class=”demo demo1”></h3>. Example show that class attribute same value can be used multiple times on same loaded HTML document on webpage and a class attribute can have the multiple values.

Now take a look at the below examples and understand.

 

Code Copied

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h2 id="demo">This is Heading</h2>
    <h2 id="demo1">This is Heading</h2>
    <h2 id="demo2">This is Heading</h2>
    <h2 id="demo3">This is Heading</h2>
    <p>Id must be unique on a webpage becuase an Id attribute of HTML Element referes unique identity of that element.</p>
</body>
</html>
 

 

Code Copied

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h2 class="demo red">This is Heading</h2>
    <h2 class="demo green">This is Heading</h2>
    <h2 class="demo blue">This is Heading</h2>
    <h2 class="demo brown">This is Heading</h2>
    <p>Class can be used multiple time with same or different type of HTML element becuase it refers  </p>

    <script>
        document.querySelectorAll("h2.demo").forEach(e=>{
            e.setAttribute("style","color:"+e.classList[1]);
        });       
    </script>
</body>
</html>


 

More examples will be covered in our YouTube Video please subscribe. Click Here to Subscribe Progrramers-YouTube Channel.

Finally, the conclusion is that querySelector() and querySelectorAll() methods are most used in any professional website. Especially in jQuery library is selector functions are built with these methods. If you find any problems or any questions in your mind please write them down in the comments. I’ll be there with the best possible solution for you. And rest programming is always about making improvements. Facebook founder & CEO Mark Zuckerberg recently told that Facebook could be more efficient than today if we would have done coding in past likewise today, we do.

I really wish to see you in my rest article.

If you want to get a clearer concept, please also subscribe progrramers YouTube Channel. Please Click on Subscribe Button.

progrramers-logo

progrramers

Hello friends! Progrramers is a tutorial site of w3 programming. If you like this tutorial site please encourages us by sharing this site links with your friends and nears & dears who want to learn web development and give us like on our Facebook page. If have any question please type in to comment box or send us message on social media sites via below given social links. Thank you, have a nice learning.

Post A Comment:

0 comments: