javascript - 如果元素存在于页面上,找到 h1 并放置在找到的元素内

标签 javascript jquery html css

有没有一种方法可以检查页面上是否存在 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/

相关文章:

javascript - 重复的 ID 值会搞乱 jQuery 选择器吗?

Javascript If/Else 语句检查内容 :url

java - 在 html 代码标签中设置文本样式

html - child 在具有 RTL 方向的 DIV 上的位置

javascript - MongoDB 查询添加和删除数组中的多个对象

javascript - 对隐藏元素感到困惑

javascript - 如何修复 SQL Inject Me 测试结果

javascript - 请求另一个域/服务器上的内容

javascript - 如何在我的网站上使用单独的 javascript 文件

javascript - jQuery 将索引编号添加到类中