Home > Web Front-end > JS Tutorial > How to use Javascript to insert tag elements inside and outside tags

How to use Javascript to insert tag elements inside and outside tags

autoload
Release: 2021-04-08 17:26:25
Original
3919 people have browsed it

How to use Javascript to insert tag elements inside and outside tags

HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>
<body>
</body>
</html>
Copy after login

1. Add elements in HTML

 <script>
        //append()创建一个列表
        const ul=document.createElement("ul");
        //循环来生成多个列表li
        for(let i=1;i<=5;i++){
            const li=document.createElement("li");
            li.textContent=`item${i}`;
            ul.append(li);
        }
        console.log(ul);
</script>
Copy after login

2. Insert inside the tag

         li= document.createElement("li");
         li.textContent="第一个元素";
        ul.insertAdjacentElement("afterbegin",li);

         li= document.createElement("li");
         li.textContent="最后一个元素";
         ul.insertAdjacentElement("beforeend",li);
Copy after login

3. Insert Outside the tag

         a=document.createElement("a");
         a.innerText="《雪中悍刀行》";
         a.href="http://www.baidu.com";
         ul.insertAdjacentElement("beforebegin",a);

         a1=document.createElement("a");
         a1.innerText="《剑来》";
         a1.href="https://www.php.cn/";
         ul.insertAdjacentElement("afterend",a1);
Copy after login

Recommended: "2021 js interview questions and answers (large summary)"

The above is the detailed content of How to use Javascript to insert tag elements inside and outside tags. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template