java-script:hello-world
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
java-script:hello-world [2023/08/08 22:21] – odefta | java-script:hello-world [2023/08/08 23:12] (current) – odefta | ||
---|---|---|---|
Line 3: | Line 3: | ||
The following script will display 'Hello World' both in a popup window and in the browser' | The following script will display 'Hello World' both in a popup window and in the browser' | ||
< | < | ||
+ | |||
+ | ===== HTML + JS code in the same file ===== | ||
<code javascript hello-world-js.html> | <code javascript hello-world-js.html> | ||
Line 21: | Line 23: | ||
</ | </ | ||
</ | </ | ||
+ | |||
+ | < | ||
+ | The **document.querySelector** method is a very useful and commonly used function in JavaScript that returns the first element within the document that matches a specified selector or group of selectors. \\ | ||
+ | The syntax looks like this: | ||
+ | <code javascript> | ||
+ | const element = document.querySelector(selector); | ||
+ | </ | ||
+ | |||
+ | Here, selector is a string containing one or more CSS selectors separated by commas. This method will return the first element that is a descendant of the document that matches the specified selectors. \\ | ||
+ | __Example 1__: | ||
+ | <code javascript> | ||
+ | <div id=" | ||
+ | <p class=" | ||
+ | </ | ||
+ | </ | ||
+ | |||
+ | You could use **document.querySelector** to select the <p> element with the class " | ||
+ | <code javascript> | ||
+ | const textElement = document.querySelector(' | ||
+ | console.log(textElement.textContent); | ||
+ | </ | ||
+ | |||
+ | Or you could select it by its parent' | ||
+ | <code javascript> | ||
+ | const textElement = document.querySelector('# | ||
+ | </ | ||
+ | |||
+ | **# | ||
+ | |||
+ | __Example 2__: | ||
+ | <code javascript> | ||
+ | <div id=" | ||
+ | </ | ||
+ | |||
+ | To select the text 'Hello World': | ||
+ | <code javascript> | ||
+ | const textElement = document.querySelector('# | ||
+ | </ | ||
+ | **# | ||
+ | |||
+ | <note important> | ||
+ | If you want to select elements with the class text that are inside an element with the ID container, use **# | ||
+ | </ | ||
+ | |||
+ | </ | ||
< | < | ||
Line 52: | Line 99: | ||
</ | </ | ||
+ | ===== HTML + JS code in separated files ===== | ||
+ | |||
+ | HTML code: | ||
+ | <code html hello-world.html> | ||
+ | < | ||
+ | <html lang=" | ||
+ | < | ||
+ | <meta charset=" | ||
+ | < | ||
+ | </ | ||
+ | < | ||
+ | < | ||
+ | <script src=" | ||
+ | </ | ||
+ | </ | ||
+ | </ | ||
+ | |||
+ | Java Script code: | ||
+ | <code javascript hello-script.js> | ||
+ | alert(' | ||
+ | const h1 = document.querySelector(' | ||
+ | console.log(h1.textContent); | ||
+ | </ | ||
+ | |||
+ | <note tip>See also [[java-script: | ||
java-script/hello-world.1691522464.txt.gz · Last modified: 2023/08/08 22:21 by odefta