2

I have DOM HTML like this

<div class="width_medium">
  <p>Text 1</p>
  <p>Text 2</p>
  <div class="video">Video</div>
  <p>Text 3</p>
  <p>Text 4</p>
</div>

And I want move away div class "video" from div "width_medium". Result will like this

<div class="width_medium">
  <p>Text 1</p>
  <p>Text 2</p>
</div>
<div class="width_medium">
  <div class="video">Video</div>
</div>
<div class="width_medium">
  <p>Text 3</p>
  <p>Text 4</p>
</div>

How can I do that with jQuery?

2
  • Hey, Can you tell me this HTML tag <div class="video">Video</div> is always fixed ? Commented May 5, 2017 at 3:55
  • $('.video').wrap('<div class="width_medium">'); Commented May 5, 2017 at 3:59

1 Answer 1

2

$(".video").unwrap();
$(".video").prevAll('p').wrapAll("<div class=width_medium></div>")
$(".video").nextAll('p').wrapAll("<div class=width_medium></div>")
$(".video").wrap("<div class=width_medium></div>")
.width_medium p {
  background-color: blue
}

.width_medium .video {
  background-color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="width_medium">
  <p>Text 1</p>
  <p>Text 2</p>
  <div class="video">Video</div>
  <p>Text 3</p>
  <p>Text 4</p>
</div>

  1. Unwrap the elements.
  2. Use .prevAll() and .nextAll() and .wrapAll() to wrapp all prev and next p
  3. Use .wrap() for the class video

UPDATE

Dont unwrap at first follow previous step then add .parent() to .video then use unwrap()

$(".video").prevAll('p').wrapAll("<div class=width_medium></div>")
$(".video").nextAll('p').wrapAll("<div class=width_medium></div>")
$(".video").wrap("<div class=width_medium></div>")
$(".video").parent().unwrap();
.width_medium p {
  background-color: blue
}

.width_medium .video {
  background-color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="width_medium">
  <p>Text 1</p>
  <p>Text 2</p>
  <div class="video">Video</div>
  <p>Text 3</p>
  <p>Text 4</p>
</div>

Sign up to request clarification or add additional context in comments.

7 Comments

This wouldn't quite work if the original div had p elements before or after it, would it?
it would work on current html markup though and that is what OP provided
Sure, but isn't there a variation to this code that could target that div regardless of what else is on the page?
@nnnnnn mate will update work base on what you ask earlier?
@nnnnnn thanks for critism it helps to make answers better and fitted for the OP
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.