有没有一种方法可以检查页面上是否存在 div 元素,如果存在,则找到该页面的 h1,将其从原处移除,然后将其添加到找到的 div 元素内?示例:
<div id="banner">
<!---find if this div exists first--->
</div>
<div class="page">
<h1>Then find this and add it instead to above banner</h1>
</div>
如果顶部横幅不存在,则页面需要保持不变。
最佳答案
使用 jquery 检查元素是否存在,然后使用 $.append()
将 h1
移动到该元素。
var $banner = $('#banner');
if ($banner.length) {
$banner.append($('.page h1'));
}
#banner h1 {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner">
<!---find if this div exists first--->
</div>
<div class="page">
<h1>Then find this and add it instead to above banner</h1>
</div>
关于javascript - 如果元素存在于页面上,找到 h1 并放置在找到的元素内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44593737/