包装的不同HTML元素选择

时间:2015-09-17 09:58:53

标签: javascript jquery html

是否可以选择多个不同的html元素并用div包装它们?

例如:

/// <summary>
/// Test class for Calculator
/// </summary>
[TestClass]
public class CalculatorTest
{
    /// <summary>
    /// Tests addition
    /// </summary>
    [TestMethod]
    public void Test_Sub()
    {
        decimal a = 1;
        decimal b = 2;
        Assert.AreEqual((a - b), Calculator.Sub(a, b));
    }
}

我可以以及如何选择这些元素吗?有任何想法吗?

试过JQuery的wrapAll,但是如果我按类名选择的话,它不会占用
元素。

2 个答案:

答案 0 :(得分:1)

函数siblings()可用于选择一个元素的所有兄弟节点。然后执行wrapAll()

var $div = $('<div>');
$('span[contenteditable]')
    .first()
    .nextUntil('span:not([contenteditable])')
    .addBack()
    .wrapAll( $div );
div{
  border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span contenteditable="false">The correct answer is (A) 1 to 2. </span> 
<span contenteditable="true" class="answers-edit"></span>
<br>
<br>
<span contenteditable="false">Choice B (2 to 3) </span>
<span contenteditable="true" class="answers-edit"></span>
<br>
<span contenteditable="false">Choice C (3 to 4) </span>
<span contenteditable="true" class="answers-edit"></span>
<br>
<span contenteditable="false">Choice D (4 to 5) </span>
<span contenteditable="true" class="answers-edit"></span>
<br>
<span contenteditable="false">Choice E (5 to 6) </span>
<span contenteditable="true" class="answers-edit"></span>
<br>
<span>I don't need this to be wrapped!</span>

答案 1 :(得分:0)

是的,这是可能的。 实施例

<p>Hello</p>
<p>cruel</p>
<p>World</p>

<script>
$( "p" ).wrapAll( "<div></div>" );
</script>