我有一个 DOM 结构,其中包含一系列这三种类型中的任何一种或所有 <p>
随机顺序的标签:
<p>Some text</p> <!-- a <p> with only text -->
<p><img src="someImg"></p> <!-- a <p> with only an <img> -->
<p> <!-- a <p> with both text and <img> -->
<img src="anotherImg">
Some other text
</p>
... <!-- Random combination of these <p> tags -->
我需要更改 DOM 结构以将所有内容放入它自己的 <div>
以及一个指示原始 <p>
是否存在的类标签只包含一件事或两件事:
<div class="single"> <!-- From <p> tag with only text -->
<p>Some text</p>
</div>
<div class="single"> <!-- From <p> tag with only an <img> -->
<img src="someImg">
</div>
<div class="double"> <!-- <img> from <p> tag with both text & <img> -->
<img src="anotherImg>
</div>
<div class="double"> <!-- <p> from <p> tag with both text & <img> -->
<p>Some other text</p>
</div>
我已经成功获得了 <p>
只有 <img>
的标签标记或文本到自己的<div>
使用 jQuery:
$('#content').find('img').each(function(index, element) {
var parentTag = $(this).parent().get(0).tagName;
if (parentTag == 'P') {
$(this).parent().contents().unwrap();
}
$(this).wrap('<div class=\"single\"></div>');
});
$('#content').find('p').each(function(index, element) {
$(this).wrap('<div class=\"single\"></div>');
});
但我无法获得 <p>
标签,其中包含图像和文本到自己单独的 <div>
带有单独类的标签。
我不一定需要使用 jQuery 来完成此操作。有什么想法吗?
最佳答案
使用querySelectorAll()
选择 p
节点。然后遍历 nodeList 以检查当前元素是否有图像和文本。对于文本验证,请使用 textContent
.
(function() {
function extractImage(el) {
var img = el.querySelector('img');
if (!img) return null;
el.removeChild(img);
return img;
}
function wrap(el, cls, isDouble) {
var img = extractImage(el);
var wrapper = document.createElement('div');
wrapper.classList.add(cls);
el.parentNode.insertBefore(wrapper, el);
if (isDouble && img) {
var imageWrapper = document.createElement('div');
el.parentNode.insertBefore(imageWrapper, el);
imageWrapper.appendChild(img);
imageWrapper.classList.add(cls);
}
el.parentNode.removeChild(el);
if (!isDouble && img) el = img;
wrapper.appendChild(el);
}
function hasImageAndText(el) {
return el.querySelector('img') && el.textContent.trim() ? true : false;
}
document.querySelectorAll('#content p:not(:empty)').forEach(el => {
if (hasImageAndText(el)) wrap(el, 'double', true);
else wrap(el, 'single');
});
})();
.single {
background-color: gold;
}
.double {
background-color: violet;
}
<div id="content">
<p>Some text</p>
<p><img src="//placehold.it/50"></p>
<p>
<img src="//placehold.it/50"> Some other text
</p>
</div>
关于javascript - 获取一系列 p 元素的内容并放置在它们自己的 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43702376/