TheEyesHaveIt
TheEyesHaveIt

Reputation: 1021

Jquery - appending elements on same line

I'm trying to align 4 elements side-by-side in a div. Two of them are images and two of them are paragraph tags.

like this:

[img1] -- [p1] -- [img2] -- [p2]

Below is my code. However, the elements are displaying vertically on top of each other. I want them to be on the same line. How can I do this?

var p1 = document.createElement("p");
var p2 = document.createElement("p");
var t1 = document.createTextNode("A");
var t2 = document.createTextNode("B");

p1.appendChild(t1);
p2.appendChild(t2);

var parent_div = document.createElement("div");
parent_div.classList.add("my_div");
$(".my_div").css('display','inline-block');
//$(".my_div").css('float','left');

var img1 = document.createElement("img");
var img2 = document.createElement("img");
img1.src = "image1.png";
img2.src = "image2.png";

parent_div.appendChild(img1);
parent_div.appendChild(p1);
parent_div.appendChild(img2);
parent_div.appendChild(p2);

Upvotes: 0

Views: 6423

Answers (2)

James Burgess
James Burgess

Reputation: 497

The reason that you children are not showing inline is because you have only set it on the parent div and not its children.

try adding this to your CSS:

.parent_div{
    display: flex;
    flex-direction: row;
    justify-content: centre/space-around/space-between;
}

or alternatively, you could set each child to have display: inline block
like this:

parent_div.appendChild(img1).classList.add("my_div");

Upvotes: 1

Obsidian Age
Obsidian Age

Reputation: 42384

Instead of giving your .my_div element a display of inline-block, you need to give the children the styling. This can be done with
$(".my_div img, .my_div p").css('display', 'inline-block'). Also, note that this has to be applied after the element is added to the page!

Or alternatively, this can be done in CSS with:

.my_div > img, .my_div > p {
  display: inline-block;
}

Which can be seen in the following example:

var p1 = document.createElement("p");
var p2 = document.createElement("p");
var t1 = document.createTextNode("A");
var t2 = document.createTextNode("B");

//p1.appendChild(pos_percent);
//p2.appendChild(neg_percent);
p1.innerHTML = 'a';
p2.innerHTML = 'b';

var parent_div = document.createElement("div");
parent_div.classList.add("my_div");

var img1 = document.createElement("img");
var img2 = document.createElement("img");
img1.src = "http://placehold.it/100";
img2.src = "http://placehold.it/100";

parent_div.appendChild(img1);
parent_div.appendChild(p1);
parent_div.appendChild(img2);
parent_div.appendChild(p2);

// Sample
var example = document.getElementById('example');
example.appendChild(parent_div);

$(".my_div img, .my_div p").css('display', 'inline-block');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="example"></div>

Upvotes: 2

Related Questions