我想使用JavaScript查找div
中的第一个链接(了解更多链接)并动态地将整个div
包装在那个href中。
如何修改此代码以便执行此操作?
$('div.textPane .DNNModuleContent.ModDNNHTMLC').wrap("<a href=''></a>", function() {
a.href = $('a:first', this).attr('href');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dnn_pane02textLeft" class="flexPane LeftPane textPane">
<div class="DnnModule DnnModule-DNN_HTML DnnModule-499 DnnVersionableControl">
<a name="499"></a>
<div id="dnn_ctr499_ContentPane" style="background-color:#f2a42a;">
<div id="dnn_ctr499_ModuleContent" class="DNNModuleContent ModDNNHTMLC">
<div id="dnn_ctr499_HtmlModule_lblContent">
<h1>Analytic Solutions</h1>
<p>Wilshire serves the investment analytic needs of institutional investors by offering a platform that combines the depth of our capabilities within...
</p>
<h5><a href="/analytics/analytic-solutions/">Learn More</a></h5>
</div>
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
克隆元素并删除文本内容然后用它包装
$('div.textPane .DNNModuleContent.ModDNNHTMLC').wrap(function() {
return $('a:first', this).clone().text('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dnn_pane02textLeft" class="flexPane LeftPane textPane">
<div class="DnnModule DnnModule-DNN_HTML DnnModule-499 DnnVersionableControl">
<a name="499"></a>
<div id="dnn_ctr499_ContentPane" style="background-color:#f2a42a;">
<div id="dnn_ctr499_ModuleContent" class="DNNModuleContent ModDNNHTMLC">
<div id="dnn_ctr499_HtmlModule_lblContent">
<h1>Analytic Solutions</h1>
<p>Wilshire serves the investment analytic needs of institutional investors by offering a platform that combines the depth of our capabilities within...
</p>
<h5><a href="/analytics/analytic-solutions/">Learn More</a></h5>
</div>
</div>
</div>
</div>
</div>
或者通过创建新标签
$('div.textPane .DNNModuleContent.ModDNNHTMLC').wrap(function() {
return $("<a/>", {
href: $('a:first', this).attr('href')
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dnn_pane02textLeft" class="flexPane LeftPane textPane">
<div class="DnnModule DnnModule-DNN_HTML DnnModule-499 DnnVersionableControl">
<a name="499"></a>
<div id="dnn_ctr499_ContentPane" style="background-color:#f2a42a;">
<div id="dnn_ctr499_ModuleContent" class="DNNModuleContent ModDNNHTMLC">
<div id="dnn_ctr499_HtmlModule_lblContent">
<h1>Analytic Solutions</h1>
<p>Wilshire serves the investment analytic needs of institutional investors by offering a platform that combines the depth of our capabilities within...
</p>
<h5><a href="/analytics/analytic-solutions/">Learn More</a></h5>
</div>
</div>
</div>
</div>
</div>