如何使用父ID或DIV替换/删除子类

时间:2017-06-22 05:28:08

标签: javascript jquery

假设我要删除abc class中包含div的{​​{1}},并将其替换为另一个类名just inside the "oneClass",请注意我不要{要更换的"xyz"内的{1}}有人可以指导我如何实现它吗?

"abc class"

应用jquery或javascript后,输出应为

"twoClass"

请在这里指导我。

5 个答案:

答案 0 :(得分:2)

使用jQuery中的child selector >直接在abc下选择类oneClass的元素。然后只需remove abc课程和add xyz课程。

$(".oneClass > .abc").removeClass("abc").addClass("xyz")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "oneClass" id = "oneId">
   <div class = "abc">
      Phil
   </div>
</div>

<div class ="twoClass" id = "twoId">
   <div class = "abc">
      Heath
   </div>
</div>

答案 1 :(得分:0)

var a = $('.oneClass');
var childEle = a.children();
Array.prototype.forEach.call(childEle,function(ele) {
    ele.classList = "xyz";
})

答案 2 :(得分:0)

<div class = "oneClass" id = "oneId">
        <div class = "abc">  // NOT ALLOWED TO ADD ANYTHING HERE
            Phil
        </div>
    </div>

    <div class ="twoClass" id = "twoId">
        <div class = "abc">  // NOT ALLOWED TO ADD ANYTHING HERE
            Heath
        </div>
    </div>

        function find(){

            $('div#oneID').childern('div').addClass('success');

            $('div#oneID').childern('div').removeClass('success');

        };

尝试这个。

答案 3 :(得分:0)

findremoveClassaddClass按照您的意愿行事。

$('.oneClass').find('.abc').removeClass('abc').addClass('xyz');
.xyz{
    width: 500px;
    margin: auto;
    border: 3px solid #73AD21;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "oneClass" id = "oneId">
        <div class = "abc">  // NOT ALLOWED TO ADD ANYTHING HERE
            Phil
        </div>
    </div>

    <div class ="twoClass" id = "twoId">
        <div class = "abc">  // NOT ALLOWED TO ADD ANYTHING HERE
            Heath
        </div>
    </div>

答案 4 :(得分:0)

正如你的问题标题是......

如何使用父ID替换/删除子类

您需要使用父div的ID

$('#oneID > .abc').removeClass('abc').addClass('xyz');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "oneClass" id = "oneId">
        <div class = "abc">  // NOT ALLOWED TO ADD ANYTHING HERE
            Phil
        </div>
    </div>

    <div class ="twoClass" id = "twoId">
        <div class = "abc">  // NOT ALLOWED TO ADD ANYTHING HERE
            Heath
        </div>
    </div>