原生js插入HTML元素

原生js插入HTML元素方法:insertAdjacentHTML
insertAdjacentHTML 语法格式
element.insertAdjacentHTML(position, text);

1)position 是相对于 element 元素的位置,并且只能是以下的字符串之一:

1.beforebegin:在 element 元素的前面;

2.afterbegin:在 element 元素的第一个子节点前面;

3.beforeend:在 element 元素的最后一个子节点后面;

4.afterend:在 element 元素的后面。

比如我们想放在element元素后面,就可以这么写,

javascript 复制代码
element('afterend',"<div>123</123>")

如果需要多次判断插入,并且删除之前插入的元素,则可以用remove方法,格式如下:根据id、className等找到这个元素,如果这个元素的id为a,

javascript 复制代码
document.getElementById(''a").remove()
javascript 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- 找出不含有重复字符的最长字串的长度 -->
    <input id="tts" type="text" placeholder="请输入字符串" value="">
    <button onclick="Selects()">筛选</button>
    <div id="one">

    </div>
    <script>
        function Selects(){
            let text=0,temp=0;
            let Texts=document.getElementById('tts').value
            for(let i=0;i<=Texts.length;i++){
                if(Texts[i]==Texts[i+1])
                {
                    if(text<temp){
                        text=temp
                    }
                    temp=0
                }else{
                    temp++;
                }
            }
            if(document.getElementById('two')){
                document.getElementById('two').remove()
            }
            document.getElementById('one').insertAdjacentHTML('afterend','<div id="two">'+text+"</div>")
            return text;
        }
    </script>
</body>
</html>
相关推荐
wuhen_n34 分钟前
网络请求在Vite层的代理与Mock:告别跨域和后端依赖
前端·javascript·vue.js
for_ever_love__36 分钟前
Objective-C学习 NSSet 和 NSMutableSet 功能详解
开发语言·学习·ios·objective-c
似水明俊德7 小时前
02-C#.Net-反射-面试题
开发语言·面试·职场和发展·c#·.net
Thera7777 小时前
C++ 高性能时间轮定时器:从单例设计到 Linux timerfd 深度优化
linux·开发语言·c++
炘爚8 小时前
C语言(文件操作)
c语言·开发语言
阿蒙Amon8 小时前
C#常用类库-详解SerialPort
开发语言·c#
凸头9 小时前
CompletableFuture 与 Future 对比与实战示例
java·开发语言
wuqingshun3141599 小时前
线程安全需要保证几个基本特征
java·开发语言·jvm
Moksha2629 小时前
5G、VoNR基本概念
开发语言·5g·php
jzlhll1239 小时前
kotlin Flow first() last()总结
开发语言·前端·kotlin