Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

如何在当前js元素前插入其他元素?

<!DOCTYPE?html>
<html?lang="zh-CN">
<head>
????<meta?charset="UTF-8">
????<meta?name="viewport"?content="width=device-width,?user-scalable=no,?initial-scale=1.0,?maximum-scale=1.0,?minimum-scale=1.0">
????<meta?http-equiv="X-UA-Compatible"?content="ie=edge">
????<title>Document</title>
</head>
<body>
    ...
    其他元素
    ...
    
    要插入元素在这个位置
????<script?src="./script.js"></script>
</body>
</html>

就比如上面的代码

我在js文件里面写了代码要创建元素,必须要插入在当前的js元素之前

有没有知道如何做?望指教一下,谢谢!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

给script一个id或者class都可,当然如果只有一个script也可以直接用标签选择器,能select即可。

var $script = document.querySelector('#insert_script')
var $el = document.createElement('div')
$el.textContent = 'insert element';

// 方法一:
// $script.parentElement.insertBefore($el, $script)
// 方法二:
$script.insertAdjacentElement('beforebegin', $el)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...