Selecting and Manipulating Elements in Javascript


By Tamer Khraisha

Selecting and manipulating elements in Javascript Among the different tasks that you want your website to perform manipulate an element or some of its features, for example:

1- Change the color of a paragraph when you click on it
2- Insert a new paragraph when you click a button
3- Make something appear when clicking on a button

To program the behavior of websites so that to perform the above tasks and others, programmers use Javascript. Javascript enables you to add powerful interactions to your website to make it more user-friendly. Let's start with the following example:


        
 <p id="intro">Hello World!</p>

 <p id="demo"></p>

 <script>
 var myElement = document.getElementById("intro");
 document.getElementById("demo").innerHTML = 
 "The text from the intro paragraph is " + myElement.innerHTML;
 </script>
        
    

In the above code we define two paragraphs, the first with id= "intro" and has Hello World! as it ' s inner text and the second is an empty paragraph with id= "demo ". Assume we want to select the second paragraph and replace it's content with a phrase that says 'The text from the intro paragraph is Hello World! '. To do this, we create a JavaScript code that is included between the script tags. In the above script, the first line creates a variable called myElement. Since the phrase 'Hello World! ' is the argument of the first paragraph, we set the content of myElement to 'Hello World! ' simply by looking through our document for the paragraph that contains this phrase. Given that the first paragraph has an id='intro' we can use the command document.getElementById("intro "). getElementById is a Javascript command that looks though our document for the element which has an id='intro'. Now myElement is a variable that has "Hello World! " as it's content. The next and final step would be to find the second paragraph and replace it's content with the phrase "The text from the intro paragraph is "Hello World! ". We can do this by selecting the empty element with id="demo" and set it's inner text equal to "The text from the intro paragraph is" plus the inner text of myElement which is "Hello World! ". This is what the second line inside the script does. Let's look at another example:


        
 <p>First Paragraph</p>
 <p>Second Paragraph</p>

 <p id="demo"></p>

 <script>
 var x = document.getElementsByTagName("p");
 document.getElementById("demo").innerHTML = 
 'The first paragraph (index 0) is: ' + x[0].innerHTML;
 </script>
        
    

The above code creates a variable that x that has inside all the paragraphs in our document. Successively, it selects the element with id="demo" and replaces it's content with the phrase "The first paragraph (index 0) is: " and the phrase that is the inner content of the first element in x, which is "First Paragraph".


It is also possible to select elements by their class name, for example the next code selects all the elements whose class names matches "intro"


        
 var x = document.getElementsByClassName("intro");
        
    

If you want to find all HTML elements with a specified CSS selector, you can use the querySelectorAll() method. Below I show two examples where in the first one we select all the paragraphs with class name "intro" and the second selects all the paragraphs with id name "intro"

        
 WITH CLASS SELECTOR      
        
 <p>Hello World!</p>

 <p class="intro">First Paragraph.</p>
 <p class="intro">Second Paragraph</p>

 <p id="demo"></p>


 <script>
 var x = document.querySelectorAll("p.intro");
 document.getElementById("demo").innerHTML = 
 'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
 </script>


 WITH ID SELECTOR      

 <p>Hello World!</p>

 <p id="intro">First Paragraph</p>
 <p id="intro">Second Paragraph</p>

 <p id="demo"></p>

 <script>
 var x = document.querySelectorAll("p#intro");
 document.getElementById("demo").innerHTML = 
 'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
 </script>
        
    

JQuery Selectors

Selecting elements in Javascript is also possible by using the Jquery library


The basic jquery selector is of the form $().For example, in the code below we define a function that looks though the document and checks if there is a button tag defined; Once the button is found, our function looks for all paragraphs in document and hide them if the button is clicked. The paragraphs in the document are found by using the command $("p")

        
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/
 jquery.min.js"></script>

 <script>
 $(document).ready(function(){
     $("button").click(function(){
         $("p").hide();
     });
 });
 </script>
 </head>
 <body>

 <h2>This is a heading</h2>

 <p>First Paragraph</p>
 <p>Second Paragraph</p>

 <button>Click me to hide paragraphs</button>
        
    

It is also possible to select elements in Jquery by their class name or id name. Next we show two examples where in the first one we select the element(s) with id name test and in the second example we select the element(s) with class name test.

        
 $(document).ready(function(){
     $("button").click(function(){
         $("#test").hide();
     });
 });


 $(document).ready(function(){
     $("button").click(function(){
         $(".test").hide();
     });
 });
        
    

An interesting property of Jquery selectors is that they can be used easily to change CSS features in our document. The example below shows how we can use Jquery to change CSS features. First we create four paragraphs each having an id and a name. Next, with the first code we take all paragraphs and change their color to yellow, while the second and third codes act only on those paragraphs whose id is 'id0' or name equal to 'name1'.

        
 <p id= "id0" name=" name">  This is a paragraph</p>
 <p id= "id1" name=" name1"> This is a paragraph</p>
 <p id= "id2" name=" name1"> This is a paragraph</p>
 <p id= "id3" name=" name1"> This is a paragraph</p>

 $('p').css('color','yellow')

 $(p[id="id0"]).css('color','yellow')

 $(p[name="name1"]).css('color','yellow')
        
    

Notice that changing CSS features is also possible without Jquery:

        
 <p id= "id0" name=" name">  This is a paragraph</p>
 <p id= "id1" name=" name1"> This is a paragraph</p>
 <p id= "id2" name=" name1"> This is a paragraph</p>
 <p id= "id3" name=" name1"> This is a paragraph</p>
        
    

To change all paragraphs'color to red we can use:
        
   var x = document.querySelectorAll('p');
   for (i = 0; i < x.length; i++) { 
   x[i].style.color='red';
 }
        
    

To change a paragraph's color if the id='id0' :

        
document.getElementById('id0).style.color='red'
        
    

More can be found on the W3Schools webpage W3Schools-Jquery Selectors

08 August 2017 – coding
20 min – 810 words
Tamer Khraisha – Email : tamer.khraisha2@gmail.com– Address : Nádor u., Budapest, 1051