如何替换元素标记,然后将其添加到现有元素
How to replace an element tag and then add it to an existing element?
我有一个<img>
标签,后跟一个<span>
标签,我将其保存在一个名为$contents
的变量中。但是,我想在使用add()
将其添加到图像标签之前,将<span>
标签替换为<figcaption>
。我似乎无法让它这样做。这是我到目前为止所拥有的:
首先是 HTML
<img src="whatever.jpg" />
<span>Copyright Stackoverflow</span>
有了这个Jquery代码:
$elem.find("img, img + span").each(function(innerIndex) {
var $contents = $(this).add($(this).next('span'));
});
我最终得到的是:
<img src="whatever.jpg" /> <span>Copyright Stackoverflow</span>
我想发生的更像是这样(如果它有效,它没有(:
$elem.find("img, img + span").each(function(innerIndex) {
// first replace the span with a figcaption
var $figcaption = $(this).next('span').unwrap().wrap('<figcaption/>');
// add the new element to the img tag to make the new contents
var $contents = $(this).add($figcaption);
});
所以我可以得到这个:
<img src="whatever.jpg" /> <figcaption>Copyright Stackoverflow</figcaption>
当我$contents
输出到页面时,我得到一个空<span>
,而不是一个包装在<figcaption>
标签中的。我应该怎么做?
更新:为了澄清,我需要将完成的 HTML 放入一个变量中,因为它稍后会在不同的地方使用。所以所有这些<img src="whatever.jpg" /><figcaption>Copyright</figcaption>
都必须在变量中。
转:
<img src="whatever.jpg" />
<span>Copyright Stackoverflow</span>
到:
<img src="whatever.jpg" />
<figcaption>Copyright Stackoverflow</figcaption>
我建议:
// selecting the relevant elements,
// using the replaceWith() method to
// replace those found elements:
$('img + span').replaceWith(function(){
// returning a string comprised of the HTML tags,
// surrounding the text from the 'this' (the current
// <span> element of the jQuery collection) node:
return '<figcaption>' + this.textContent + '</figcaption>'
});
$('img + span').replaceWith(function(i, el) {
return '<figcaption>' + this.textContent + '</figcaption>'
});
span {
color: limegreen;
}
figcaption {
color: #f90;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="whatever.jpg" />
<span>Copyright Stackoverflow</span>
JS小提琴演示。
或者,为了在任何子元素上保留事件处理程序:
// a simple function bound to the click event
// on the <span> element within a parent <span>
// element:
$('span > span').click(function () {
console.log('woo');
})
// finding the relevant <span> elements:
$('img + span').replaceWith(function () {
// returning a created <figcaption> element,
// after appending the contents of the
// found <span> element(s):
return $('<figcaption>').append($(this).contents());
});
$('span > span').click(function() {
console.log('woo');
})
$('img + span').replaceWith(function() {
return $('<figcaption>').append($(this).contents());
});
span {
color: limegreen;
}
figcaption {
color: #f90;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="whatever.jpg" />
<span><span>Copyright</span> Stackoverflow</span>
JS小提琴演示。
或者,在原生 JavaScript 中:
// creating a named function, and its arguments:
function replaceWith(original, tag) {
// tag: String, the element-type to be created,
// here we remove any '<' or '>' characters, to
// ensure that '<fieldset>' becomes 'fieldset':
tag = tag.replace(/<|>/g, '');
// creating a new element of that type:
var newEl = document.createElement(tag);
// setting the innerHTML of the created element
// that of the original element:
newEl.innerHTML = original.innerHTML;
// replacing the original child with the new element:
original.parentNode.replaceChild(newEl, original);
}
// finding the relevant elements:
var elements = document.querySelectorAll('img + span'),
// converting the collection of elements into an
// an Array:
elementArray = Array.prototype.slice.call(elements, 0);
// iterating over the Array using Array.prototype.forEach():
elementArray.forEach(function (elem) {
// calling the function, passing in the current array-element
// of the array over which we're iterating:
replaceWith(elem, '<figcaption>')
});
function replaceWith(original, tag) {
tag = tag.replace(/<|>/g, '');
var newEl = document.createElement(tag);
newEl.innerHTML = original.innerHTML;
original.parentNode.replaceChild(newEl, original);
}
var elements = document.querySelectorAll('img + span'),
elementArray = Array.prototype.slice.call(elements, 0);
elementArray.forEach(function(elem) {
replaceWith(elem, '<figcaption>')
});
span {
color: limegreen;
}
figcaption {
color: #f90;
}
<img src="whatever.jpg" />
<span>Copyright Stackoverflow</span>
JS小提琴演示。
此外,如果您希望在子元素上保留事件处理程序 - 使用本机JavaScript:
// finding the <span> elements with a <span> parent:
document
.querySelector('span > span')
// adding a simple anonymous function as the
// handler for the click event:
.addEventListener('click', function () {
// logging a simple message to the console:
console.log('woo')
});
function replaceWith(original, tag) {
tag = tag.replace(/<|>/g, '');
var newEl = document.createElement(tag);
// this is the only change, while the
// original element contains a firstChild node
// we append that child-node to the newly
// created-element:
while (original.firstChild) {
// using Node.appendChild to move the firstChild
// of the original node into the created-element:
newEl.appendChild(original.firstChild)
}
original.parentNode.replaceChild(newEl, original);
}
var elements = document.querySelectorAll('img + span'),
elementArray = Array.prototype.slice.call(elements, 0);
elementArray.forEach(function (elem) {
replaceWith(elem, '<figcaption>')
});
document.querySelector('span > span').addEventListener('click', function() {
console.log('woo')
});
function replaceWith(original, tag) {
tag = tag.replace(/<|>/g, '');
var newEl = document.createElement(tag);
while (original.firstChild) {
newEl.appendChild(original.firstChild)
}
original.parentNode.replaceChild(newEl, original);
}
var elements = document.querySelectorAll('img + span'),
elementArray = Array.prototype.slice.call(elements, 0);
elementArray.forEach(function(elem) {
replaceWith(elem, '<figcaption>')
});
span {
color: limegreen;
}
figcaption {
color: #f90;
}
<img src="whatever.jpg" />
<span><span>Copyright</span> Stackoverflow</span>
JS小提琴演示。
引用:
- JavaScript:
-
Array.prototype.forEach()
. -
Array.prototype.slice()
. -
document.createElement()
. -
document.querySelectorAll()
. -
Function.prototype.call()
. - JavaScript 正则表达式指南。
-
Node.innerHTML
. -
Node.replaceChild()
. -
String.prototype.replace()
.
-
- j查询:
-
append()
. -
contents()
. -
replaceWith()
.
-
$(function() {
//create figcaption empty
var figcaption = $('<figcaption/>');
//get span
var span = $('span:first');
//replacement behind the scenes
figcaption.html(span.html());
//replace in dom
span.replaceWith(figcaption);
//verify
alert($('body').html());
});
https://jsfiddle.net/rodrigo/Lfvotuze/
尝试类似操作:
$elem.find("img").each(function(innerIndex) {
var span = $(this).next('span');//gets the next span from the img
var $contents = span.text();//gets the content
span.remove();//removes the span
//adds the figcaption after the img tag
$(this).after('<figcaption>'+$contents+'</figcaption>');
});
JSFIDDLE: https://jsfiddle.net/t5dLcw12/
这其实很简单。 用我们的新标签包裹跨度内部,然后解开该新标签的包装删除跨度,然后创建这两个标签的克隆(myclone
现在包含您的"新"元素(:
$('span').wrapInner('<figcaption/>').find('figcaption').unwrap();
var myclone = $('img').add('figcaption').clone();
一条链条也是如此:
var myclonea = $('span').wrapInner('<figcaption/>').find('figcaption').unwrap().add('img').clone();
注意 关于原始包装器上可能需要移动到新包装器等的事件处理程序,如果需要,您可以参考这篇文章:jQuery 查找向对象注册的事件处理程序
- 将事件侦听器添加到文档,而不是签入元素存在,然后添加事件侦听器
- 将元素移动到右侧,然后返回到左侧
- 添加animate.css类,然后使用remove移除元素
- Angular js,在选择元素上,我想 POST 数据以将其保存在数据库中,然后我想使用 PUT 更新它而无需重新加载
- 在元素中搜索字符串,然后将其放入条件语句中
- 从异步调用返回数组,然后为数组的每个元素返回其他异步调用
- JQuery 测试元素是可见的还是隐藏的,然后添加删除类
- 为什么这个脚本只工作一次?只替换元素一次,然后再也不替换
- 如何删除元素的结束标记,添加一些文本,然后重新添加标记
- jQuery检查URL,然后显示和隐藏元素
- Javascript(动态)插入到数组中,然后移动+1下面的所有元素
- jQuery-等待此元素,然后执行1次
- 如何正确地等待元素获得正确的宽度,然后在Angular 2中访问它
- ()插入元素,然后将其取回
- 从数组中删除元素,然后保留其状态以备将来使用,而不使用全局变量
- jQuery查找元素,然后组成逗号分隔的列表
- 使用Raphael.js可以相对定位一个元素,然后将其偏移一个绝对单位
- 我如何让我的网站检测鼠标是否被使用,然后在元素中添加一个类
- 关于在动态创建的元素中添加预先样式化的类或在那里添加stying&然后
- 按类和自定义属性值查找元素(然后更新它)