如何替换元素标记,然后将其添加到现有元素

How to replace an element tag and then add it to an existing element?

本文关键字:元素 然后 添加 何替换 替换      更新时间:2023-09-26

我有一个<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 查找向对象注册的事件处理程序