Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery选择元素的父元素并对其使用prependTo()_Javascript_Jquery_Html_Jquery Selectors_Parent - Fatal编程技术网

Javascript jQuery选择元素的父元素并对其使用prependTo()

Javascript jQuery选择元素的父元素并对其使用prependTo(),javascript,jquery,html,jquery-selectors,parent,Javascript,Jquery,Html,Jquery Selectors,Parent,我正在尝试重组元素。我面临的问题是元素没有唯一的类或ID。因此,例如,如果调用.prependTo,它显然会移动所有匹配的元素。HTML看起来像这样(重要:真实场景包含数百个元素): 如何将函数限制为其父函数?您的代码错误,因为它选择了所有.text parent,并将每一个插入另一个。您需要使用.each()循环通过.text3,并在函数中选择元素的相关父元素 $('.text3').each(function(){ $(this).parent().prepend(this); //

我正在尝试重组元素。我面临的问题是元素没有唯一的类或ID。因此,例如,如果调用
.prependTo
,它显然会移动所有匹配的元素。HTML看起来像这样(重要:真实场景包含数百个
  • 元素):


    如何将函数限制为其父函数?

    您的代码错误,因为它选择了所有
    .text parent
    ,并将每一个插入另一个。您需要使用
    .each()
    循环通过
    .text3
    ,并在函数中选择元素的相关父元素

    $('.text3').each(function(){
      $(this).parent().prepend(this);
      // Or
      $(this).parent('.text-parent').prepend(this);
      // Or
      $(this).prependTo($(this).parent('.text-parent'));
    });
    
    $('.text3')。每个(函数(){
    $(this.parent().prepend(this);
    });
    
    .text父项{边框:1px实心#000}
    .text parent>.text3{color:red}
    
    
    • 例子 例2 例3
    • 例子 例2 例3
    • 例子 例2 例3
    您可以使用

    在目标之前插入匹配元素集中的每个元素

    $(“.text3”)。每个(函数(){
    $(this.insertBefore($(this.sillides('.text1'));
    })
    
    
    • 例子 例子 例3
    • 例子 例子 例3
    • 例子 例子 例3

    是否要将每个
    .text3
    移动到“
    .text1
    之前?
    $('.text3').parent('.text-parent').prependTo('.text-parent');
    
    $('.text3').each(function(){
      $(this).parent().prepend(this);
      // Or
      $(this).parent('.text-parent').prepend(this);
      // Or
      $(this).prependTo($(this).parent('.text-parent'));
    });
    
     $(this).insertBefore($(this).siblings('.text1'));