Document Query Selector JavaScript
In This Article I will show you How to use document.querySelector
In this Javascript Sample Code i will Create 1 function
- When the Button is Click This function will replace the existing text and add a new CSS Class .
Add Class and Modify Content
This is the Original Text
When the Button is Press it will change the Text and add a new CSS Class
JavaScript Code Snippet
document.querySelector('.theButton').addEventListener('click', function(){ // This query Selector will sellect the Class= "textCon" and replace the Existing Value with the // the new Value" Text Is Change " value listed below document.querySelector('.textCon').textContent = "Text Is Change"; // This query Selector will select the div class tri and add a new Class Value named "triangle-right" document.querySelector('.tri').classList.add('triangle-right'); });
CSS Code Snippet
.textCon{ position:absolute; left: 500px; transform: translateX(-50%); color: #555; font-size: 15px; font-family: 'Lato'; text-align: center; padding: 10px; width:160px; margin-top: 10px; } .triangle-right { width: 0; height: 0; margin-top: 10px; border-top: 25px solid transparent; border-left: 50px solid #555; border-bottom: 25px solid transparent; } .texth{ margin-top: 100px; }
HTML Code Snippet
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css"> <link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css"> <link type="text/css" rel="stylesheet" href="stylo.css"> </head> <body> <h2>Add Class and Modify Content</h2> <div class="modifi"> <p> <div class="textCon">This is the Original Text</div> </P> <div class="tri"> </div> </div> <div class="texth"> </div> <button class="theButton">Add Class and Change Text</button> <P> When the Button is Press it will change the Text and add a new CSS Class </P> <script src="jv.js"></script> </body> </html>
Check out Modify Object Literal Properties In JavaScript here