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

Jer*_*rpl 0 html javascript css jquery

有没有办法检查页面上是否存在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>
Run Code Online (Sandbox Code Playgroud)

如果顶部横幅不存在,那么页面将需要保持不变.

Mic*_*ker 5

使用jquery,检查元素是否存在,然后使用$.append()移动h1到该元素.

var $banner = $('#banner');

if ($banner.length) {
  $banner.append($('.page h1'));
}
Run Code Online (Sandbox Code Playgroud)
#banner h1 {
  color: red;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)