用jquery将文本更改为h1?

时间:2016-06-13 08:24:36

标签: javascript jquery html jquery-selectors

如何将h1文字转换为<div class="productPrice"> <span>2 990 kr</span> </div>

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

替代1 http://api.jquery.com/html/

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

替代2 http://api.jquery.com/text/

{{1}}

3 个答案:

答案 0 :(得分:1)

使用.wrapAll()

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

答案 1 :(得分:1)

.wrapInner()方法可以使用。

  

围绕匹配元素集中每个元素的内容包装HTML结构。

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

&#13;
&#13;
$('.productPrice span').wrapInner('<h1 />')
&#13;
<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>
&#13;
&#13;
&#13;

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

  

围绕匹配元素集中的每个元素包装HTML结构。

&#13;
&#13;
$('.productPrice span').wrap('<h1 />')
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

虽然使用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>