Home > Mobile >  Jquery put elements in div
Jquery put elements in div

Time:12-30

You need to put items in a div - <div style = 'flex-direction: column;'>.

Div needs to be created after p withid = "billing_city_field" and closes after the p withid = "apartment_field". Tried to do it with this function:

 jQuery (document) .ready (function ($) {
     $ ("# billing_city_field"). after ("<div style = 'flex-direction: column;'>");
     $ ("# apartment_field"). after ("</ div");
 });

But the div immediately closes. What should I do?

CodePudding user response:

Question is not super clear but from what I can tell. I think you have small misunderstanding what .after does with jQuery. After in this case is "structural" and not "time" related. If you check jQuery docs (https://api.jquery.com/after/) for this you can see basically what you need to do.

Simplest way to do this, if these things needs to created and don't exist already on body for example.

$(function(){
   var p = $("<p id='apartment_field'>Paragraph test</p>");
   $("body").append("<div id='billing_city_field' style='flex-direction: column;'></div>");
   $("#billing_city_field").html(p);
});

I've added Paragraph test so result is visible easier.

And one more thing, not sure if it's error with copy/paste but make sure that # and id don't have space in-between like this.

$("#billing_city_field")
$("#apartment_field")

Edit: Looking at the comments maybe something like this, if they exist already? You should clarify the question more.

$("#billing_city_field").append($("#apartment_field").detach());

CodePudding user response:

The issue is because you cannot append start/end tags separately. The DOM works with elements as a whole, so you need to create the entire div element in a single operation.

Given the description of your goal it looks like you're trying to wrap the existing content in a new div. As such you can use nextUntil() (assuming the target elements are siblings) and then wrapAll(). Try this:

jQuery($ => {
  let $contents = $("#billing_city_field").nextUntil('#apartment_field').add('#apartment_field');
  $contents.wrapAll('<div  />');
});

Note the use of a class attribute in the above example, instead of applying inline style rules.

  • Related