html Javascript 18 - DOM选择器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html Javascript 18 - DOM选择器相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Javascript Tutorial</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    <body style="background-color: rgb(0, 255, 221)">
    
        <h1 id="title">Javascript Tutorial</h1>
        <a href="https://google.com">Link to Google</a>
        <h4>Have fun!</h4>

        <h2 class="list-title">An Unordered HTML List</h2>

        <ul>
        <li>Coffee</li>
        <li>Tea</li>
        <li>Milk</li>
        </ul>  

        <h2 class="list-title">An Ordered HTML List</h2>

        <ol>
        <li>Coffee</li>
        <li>Tea</li>
        <li>Milk</li>
        </ol> 


    </body>
    <script>
        // 5 DOM Selector methods - Ways to select elements using the DOM
        
        //Get a single element by its ID.
        var titleElement = document.getElementById("title");
        console.log(titleElement); 
        console.dir(titleElement); //console.dir gives us what it would look like in actual javascript(object notation)

        //Access multiple elements by their class name and return as a special kind of array(HTML Collection)
        var listElements = document.getElementsByClassName("list-title");
        console.log(listElements); //We dont need to use dir in this case.
        console.log(listElements[1]); //Can access individual elements like we would with an array

        //Works like getElementsByClassName but instead with tags
        var liTags = document.getElementsByTagName("li"); //Gets all of the li elements
        console.log(liTags);

        var queryTag = document.querySelector("#title"); //Query selector uses the CSS selectors to find elements
        var queryTag = document.querySelector(".list-title"); //Classes too obviously. Only returns the first one found if multiple

        var queryTags = document.querySelectorAll(".list-title"); //This is used if you want multiple elements

        titleElement.style.color = "red";

    </script>
</html>

以上是关于html Javascript 18 - DOM选择器的主要内容,如果未能解决你的问题,请参考以下文章

do while javascript - 猜谜游戏的循环

html 如何清除JavaScript中的div,来自http://stackoverflow.com/questions/3450593/how-do-i-clear-the-content-of-

python代码优化

JavaScript练习

do...while

html Javascript 18 - DOM选择器