使用 jquery 将文本更改为 h1?

Change text to h1 with jquery?

如何将 2990 kr 文本变成 h1

<div class="productPrice">
<span>2 990 kr</span>
</div>

备选方案 1 http://api.jquery.com/html/

$(".productPrice").html("h1");

备选方案 2 http://api.jquery.com/text/

 $(".productPrice").text("h1");

使用.wrapAll():

$('.productPrice span').wrapAll('<h1></h1>');

.wrapInner()方法可以用

Wrap an HTML structure around the content of each element in the set of matched elements.

 $('.productPrice span').wrapInner('<h1 />')

$('.productPrice span').wrapInner('<h1 />')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productPrice">
<span>2 990 kr</span>
</div>

上述解决方案将产生无效的 <span><h1>...</h1></span>。而是使用 wrap()

Wrap an HTML structure around each element in the set of matched elements.

$('.productPrice span').wrap('<h1 />')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productPrice">
<span>2 990 kr</span>
</div>

虽然使用 jQuery 很容易做到这一点:

// selecting the '.productPrice' elements, and
// and wrapping the inner content (to avoid
// creating an <h1> element within a <span>:
$('.productPrice').wrapInner('<h1></h1>');

这当然也可以用普通的 JavaScript:

// creating a function that takes two arguments,
// toWrap: the Node whose contents should be wrapped,
// wrapWith: the element-type with which those contents
//           should be wrapped:
function wrapInner(toWrap, wrapWith) {

    // retrieving the contents of the element to wrap:
    var contents = toWrap.childNodes,

        // the newly-created element type:
        newElem = document.createElement(wrapWith);

    // inserting the new element before the first of the
    // the node's childNodes:
    toWrap.insertBefore(newElem, contents[0]);

    // while contents exist:
    while (contents.length) {
      // move the first of those contents into the
      // new element:
      newElem.appendChild(contents[0]);
    }
}

// retrieving the '.productPrice' elements with
// document.querySelectorAll(); and converting
// Array-like NodeList into an Array, using
// Array.from():
var elements = Array.from( document.querySelectorAll('.productPrice') );

// iterating over the array of elements, using
// Array.prototype.forEach():
elements.forEach(function (el) {
    // calling the function, passing the node
    // and the string for the replacement-element:
    wrapInner(el, 'h1');
});

function wrapInner(toWrap, wrapWith) {
  var contents = toWrap.childNodes,
    newElem = document.createElement(wrapWith);
  toWrap.insertBefore(newElem, contents[0]);
  while (contents) {
    newElem.appendChild(contents[0]);
  }
}

var elements = Array.from(document.querySelectorAll('.productPrice'));

elements.forEach(function(el) {
  wrapInner(el, 'h1');
});
<div class="productPrice">
  <span>2 990 kr</span>
</div>