首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用纯javascript操纵dom

用纯javascript操纵dom
EN

Stack Overflow用户
提问于 2018-07-03 04:57:07
回答 1查看 387关注 0票数 1

在此之前,我想说我是一个后端开发人员,实际上只使用Javascript进行表单验证。

我被指派使用“纯Javascript”来操纵DOM来使用语义HTML5标签。我被告知,分配任务的人担心我“使用了HTML知识,而不是请求的Javascript”。在查看我使用的javascipt代码时,有人知道“我使用了HTML知识而不是请求的Javascript”是什么意思吗?我知道Javascript是内联的,但这是页面模板需要我添加它的地方。

任何意见或答案都将不胜感激。

以下是该页面。我在"use strict“行下面添加了代码。

代码语言:javascript
复制
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>Animal Facts</title>
        <style>
            body{
                font-size:1.2rem;
                font-family:helvetica, arial, sans-serif;
            }
            figure img{max-width:100%;height:auto}
        </style>
    </head>
    <body>
        <div>
            <h1>Animal Facts</h1>

            <div class="image">
                <img src="http://via.placeholder.com/500x300" alt="Lorem Ipsum"/>   
                <div class="caption">Placeholder Image</div>
            </div>

            <div class="animal-facts">
                <div class="description">Bear Facts</div>
                <h1>Unlike Many Mammals...</h1>
                <ul>
                    <li>Polar bears are the largest land predators on earth,standing over 11' high and weighing over 1,700 lbs.</li>
                    <li>The giant panda is actually a bear.</li>
                    <li>Bears have an excellent sense of smell, better than dogs or possibly any other mammal.</li>
                </ul>
            </div>
            <div class="animal-facts">
                <div class="description">Tiger Facts</div>
                <h1>Interesting information about tigers</h1>
                <ul>
                    <li>Tigers are the largest wild cats in the world. Adults can weigh up to 363kg – that’s about the same as ten ten year olds! – and measure up to 3.3m!</li>
                    <li>Tigers are carnivores, eating only meat. They mainly feed on large mammals such as deer, wild pigs, antelope and buffalo.</li>
                    <li>Did you know that we have a FREE downloadable tiger primary resource? Great for teachers, homeschoolers and parents alike!</li>
                    <li>Tigers are solitary hunters, and generally search for food alone at night. They quietly stalk their prey until they are close enough to pounce – then they kill their victim with a bite to the neck or back of the head. Ouch!</li>
                    <li>Unlike most members of the cat family, tigers like water. They are good swimmers and often cool off in pools or streams.</li>
                    <li>When a tiger wants to be heard, you’ll know about it, gang – because their roar can be heard as far as three kilometres away.</li>
                    <li>They may be big and heavy, but tigers are by no means slow movers. In fact, at full speed they can reach up to 65km/h!</li>
                    <li>These fierce felines have walked the earth for a long time. Fossil remains of tigers found in parts of China are believed to be 2 million years old. Yikes!</li>
                    <li>Every tiger in the world is unique – no two tigers have the same pattern of stripes.</li>
                    <li>Today, there are five subspecies of tiger: Bengal, South China, Indochinese, Sumatran and Siberian. Sadly, three subspecies of tiger have become extinct – Caspian, Bali and Javan.</li>
                    <li>Less than 100 years ago, tigers could be found throughout Asia. Sadly, hunting and habitat loss have put populations at risk, and today their range has been reduced to around 7% of its former size. That’s why we need to do all we can to protect these beautiful beasts!</li>
                </ul>
            </div>
        </div>
<script type="text/javascript">

     "use strict";

    /** Put Javascript code here **/
    /**Create variables to store current tags that will be reused after the conversion **/
    var div = document.getElementsByTagName('div')[0];
    var ulTiger = document.getElementsByTagName('ul')[1];
    var ulBear = document.getElementsByTagName('ul')[0];
    var h1Tiger = document.getElementsByTagName('h1')[2]
    var h1Bear = document.getElementsByTagName('h1')[1];
    var h1Main = document.getElementsByTagName('h1')[0];
    var body = document.body

    /**Create variables for the new Semantic HTML5 tags that will be in the page after the conversion **/
    var Main = document.createElement('main');
    var detailsTiger = document.createElement('details');
    var detailsBear = document.createElement('details');
    var summaryTiger = document.createElement('summary');
    var summaryBear = document.createElement('summary');
    var figCaption = document.createElement('figcaption');
    var figure = document.createElement('figure');

    /**Set the first div into a variable so that the <main> can replace the  outer <div> after the conversion
       This is done so that I can create the main tag with all of its contents prior to removing the outer <div>
       from the document **/
    var child = document.getElementByTagName('div')[0];

    /**Add the text and image to the figure tag and Append the figcaption tag to it **/
    figCaption.textContent = 'Placeholder Image';
    figure.innerHTML = '<img src="http://via.placeholder.com/500x300" alt="Lorem Ipsum">';
    figure.append(figCaption);

    /**Add the animal <detail> and <summary> tags in the correct order
    summaryTiger.innerText = 'Tiger Facts';
    detailsTiger.appendChild(ulTiger);

    ulTiger.insertAdjacentElement("beforebegin", summaryTiger);

    ulTiger.insertAdjacentElement("beforebegin", h1Tiger);


    summaryBear.innerText = 'Bear Facts';
    detailsBear.appendChild(ulBear);
    ulBear.insertAdjacentElement("beforebegin", summaryBear);

    ulBear.insertAdjacentElement("beforebegin", h1Bear);


    /** Insert the new <main> tag into the <body> before the outer <div>. This is done so that 
        the new Semantic HTML5 tags are created and placed prior to removing the <div> tags 
        from the document**/
    body.insertBefore(Main, div);

    /** Insert the new <details> tags and their contents into the new <main> element **/
    Main.append(detailsTiger);
    Main.insertBefore(detailsBear, detailsTiger);
    Main.insertBefore(figure, detailsBear);
    Main.insertBefore(h1Main, figure);

    /** Now that all of the new Semantic HTML5 tags have been added, we can remove the outer <div> 
        and all of its contents from the document **/
    body.removeChild(child);

</script>
</body>
</html>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-03 05:39:26

由于这是一项作业,我认为不应该给你确切的解决方案,而是试着通过看例子来学习。理解事物,并进行实验。

为了尝试帮助你,下面是我将如何做到这一点,但不是使用你的作业中描述的每一个步骤:

代码语言:javascript
复制
/*
 * Replaces all DOM elements matching the given selector
 * with an element using the given tagName
 */
function replaceElements(selector, tagName) {
    // For every element matching the selector
    Array.from(document.querySelectorAll(selector)).forEach(function (el) {
        // Create an element with the new tagName
        var wrapper = document.createElement(tagName);
        // Insert it before the element to replace
        el.insertAdjacentElement("beforebegin", wrapper);
        // Transfer child nodes
        while (el.childNodes.length > 0) {
            wrapper.appendChild(el.childNodes[0]);
        }
        // Remove the old element
        el.parentNode.removeChild(el);
    });
}

// Replace the outer div with a main element
replaceElements('body>div:first-of-type', 'main');

// Replace image figure and caption
replaceElements('.image', 'figure');
replaceElements('.caption', 'figcaption');

// Replace details and summaries
replaceElements('.description', 'summary');
replaceElements('.animal-facts h1', 'detail');
// Switch their order
Array.from(document.querySelectorAll('summary')).forEach(function (summary) {
    summary.parentNode.insertBefore(summary.nextElementSibling, summary);
});

正如其他人所说,使用“纯JavaScript”意味着您不使用任何库,如jQuery。当然,这只是一种比喻,因为jQuery实际上只不过是纯Javascript本身。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51143637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档