Adding child to parent in Jquery using variables - javascript

I'm trying to dynamically creating a div inside a div using Jquery. When I dump the child nodes for div1, it shows only text and strong. I was expecting 'div1' to have main_div_elem child and main_div_elem to have col_md_8_elem child.
Can someone help me to add col_md_8_elem to be child of main_div_elem and main_div_elem as child of 'div1'?
Output of console log from my JS function.
NodeList [ #text "Here", ]
Code:
var id = 1;
function tryThis() {
$( "#div1" ).append( "<strong>Hello</strong>" );
var main_div_elem = $('<div /', {id : 'main_div_elem'.concat(id), "class" : "row"});
var col_md_8_elem = $('<div /', {id : 'col_md_8_elem'.concat(id), "class" : "col-md-8"});
main_div_elem.append(col_md_8_elem);
$('#div'.concat(id)).append(main_div_elem);
var children = document.getElementById("div1").childNodes;
console.log(children);
}
Trying to achieve following HTM code using jquery.
<div class="row">
<div class="col-md-8">
</div>
</div>
Thanks,
Deepak

Hello You can try the below code .I write it differently but hope it will help you
$(document).ready(function() {
var id = 1;
var main_div_elem = "<div id=main_div_elem class='row'></div>"
var main_div_elem8 = "<div id='col_md_8_elem' class='col-md-8'></div>"
$("#div1").append(main_div_elem);
$("#main_div_elem").append(main_div_elem8);
var children = $("#div1").html();
console.log(children);
});
#div1 {
height: 100px;
width: 100px;
position: absolute;
padding: 10px;
background-color: red;
}
#main_div_elem {
height: 50px;
width: 50px;
position: absolute;
padding: 10px;
background-color: green;
}
#col_md_8_elem {
height: 20px;
width: 20px;
position: absolute;
padding: 10px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="div1"></div>

Your main_div_elem and col_md_8_elem are not created correctly. The first parameters to the $(..) call are invalid HTML. You need to add a closing angle bracket (>) like this:
var id = 1;
function tryThis() {
$("#div1").append("<strong>Hello</strong>");
var main_div_elem = $('<div />', {
id: 'main_div_elem'.concat(id),
"class": "row"
});
var col_md_8_elem = $('<div />', {
id: 'col_md_8_elem'.concat(id),
"class": "col-md-8"
});
main_div_elem.append(col_md_8_elem);
$('#div'.concat(id)).append(main_div_elem);
var children = $("#div1").html();
console.log(children);
}
$(function() {
tryThis();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1"></div>

Related

How to change content of div on hover using JQuery/Javascript

I'm trying to change the contents of a div when it's hovered over using JQuery. I've seen answers on stack overflow, but I can't seem to get it working.
I've tried
$( "imgDiv" ).mouseover(
function() {
$("tdiv").textContent = "hovering";
},
function() {
$("tdiv").textContent = 'title';
}
);
I've also replaced "mouseover" with "hover". I've used a variable and the actual div in place of "imgDiv".
This is what my code looks like:
imgDiv = document.getElementById('imgDiv');
tDiv = document.getElementById('titleDiv');
$( "imgDiv" ).mouseover(
function() {
$("tdiv").textContent = "hovering";
}, function() {
$("tdiv").textContent = 'title';
}
);
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id=titleDiv>title</div>
</div>
You can use jQuery's .hover() function along with the .text() function to do what you want. Also, no need for document.getElementById:
$("#imgDiv").hover(
function() {
$("#titleDiv").text("hovering");
},
function() {
$("#titleDiv").text('title');
}
);
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id="titleDiv">title</div>
</div>
You can target the div with jQuery, and store it's original value. On mouseout, you can restore it. Also using mouseenter reduces the number of times the logic processes as mouseover will fire for every mouse move over the element.
var $titleDiv = $('#titleDiv');
$("#imgDiv")
.on('mouseenter', function() {
$titleDiv.data('originalText', $titleDiv.text());
$titleDiv.text('hovering');
})
.on('mouseout', function() {
$titleDiv.text($titleDiv.data('originalText'));
});
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id="titleDiv">title</div>
</div>
First of all, replace $("imgDiv") with $("#imgDiv") to get the element with id (#) imgDiv.
Then $("tdiv") doesn't exist, you probably mean $("div") to select a <div>tag in your DOM.
And finally, $("tdiv").textContent doesn't exist. You can try $("div").html() or $("div").text() to get the <div> tag content
--
Quick reminder : jQuery documentation on selectors
$("div") will select the <div> tags
$(".element") will select tags with class="element"
$("#element") will select tags with id="element"
You need to try like this
$( "#imgDiv" ).mouseover(function() {
$("#titleDiv").text("hovering");
}).mouseleave( function() {
$("#titleDiv").text('title');
});
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id=titleDiv>title</div>
</div>
Easy solution,
var s = document.getElementsByTagName('div');
function out() {
s[0].innerHTML = 'hello';
}
function ibn() {
s[0].innerHTML = 'Myname';
}
<div onmouseout = 'out()' onmouseenter = 'ibn()'> Myname </div>
You cannot call reference a dom with pure Javascript and them manipulate it with jQuery - it will not work.
Try this:
$( "#imgDiv" ).mouseover(function() {
$("#titleDiv").text("hovering");
});
The titleDiv id has to be referenced in your code using "#", then the id name.
Also, use $("#name_of_id").text("your content") instead of .textContent()

Why does replaceWith cancels calls to its variable?

I'm trying to clone dom elements and change their tags. But after I replace the main element I cannot change its children nor apply some click events.
I commented line after which it stops working.
Thanks for help!
http://codepen.io/sanns/pen/eJvzBN?editors=101
var selectDom = $('select');
selectDom.each(function() {
var clone = $(this).clone().insertAfter(this);
//take classes from clone
var classesStr = clone.attr('class');
clone = clone.replaceWith(function(index, oldHTML) {
return $('<div class="custom-select ' + classesStr + '">').html(oldHTML);
});
//why does not work?
clone.find('option').replaceWith(function(index, oldHTML) {
return $('<li>').html(oldHTML);
});
clone.wrapInner('<ul class="scrollbox"></ul>').prepend('<span class="shower"> Выберитеtttttttttteeeee тратататататат</span>');
//BEHAVIOR SELECT
clone.on('click', function() {
alert('asdf');
});
});
Actually .replaceWith() returns the original jQuery object, not the replacement with something.
You can find more details : http://api.jquery.com/replacewith/
Here is the small example of it:
$( "button" ).click(function() {
$( this ).replaceWith( "<div>" + $( this ).text() + "</div>" );
});
button {
display: block;
margin: 3px;
color: red;
width: 200px;
}
div {
color: red;
border: 2px solid blue;
width: 200px;
margin: 3px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>First</button>
<button>Second</button>
<button>Third</button>

How to prevent parent click event when the user clicks on his child element? AngularJS

I have a <div> with a ng-click but this <div> have a child element with also a ng-click directive.
The problem is that the click event on the child element trigger also the click event of the parent element.
How can I prevent the parent click event when I click on his child?
Here is a jsfiddle to illustrate my situation.
Thank you in advance for your help.
EDIT
Here is my code:
<body ng-app ng-controller="TestController">
<div id="parent" ng-click="parentClick()">
<div id="child" ng-click="childClick()"></div>
<p ng-bind="elem"></p>
</div>
<div><p style="text-align:center" ng-bind="childElem"></p></div>
</body>
<script>
function TestController($scope) {
$scope.parentClick = function() {
$scope.elem = 'Parent';
}
var i = 1;
$scope.childClick = function() {
$scope.elem = 'Child';
$scope.childElem = 'Child event triggered x' + i;
i++;
}
}
</script>
You should use the event.stopPropagation() method.
see: http://jsfiddle.net/qu86oxzc/3/
<div id="child" ng-click="childClick($event)"></div>
$scope.childClick = function($event) {
$event.stopPropagation();
...
}
Use event.stopPropagation to stop the event from bubbling up the DOM tree from child event handler.
Updated Demo
function TestController($scope) {
$scope.parentClick = function() {
$scope.elem = 'Parent';
}
var i = 1;
$scope.childClick = function(e) {
$scope.elem = 'Child';
$scope.childElem = 'Child event triggered x' + i;
i++;
e.stopPropagation(); // Stop event from bubbling up
}
}
body {
width: 100%;
height: 100%;
overflow: hidden;
}
#parent {
width: 100px;
height: 100px;
position: relative;
z-index: 1;
margin: 10px auto 0 auto;
background-color: #00acee;
border-radius: 2px;
cursor: pointer;
}
#parent:hover {
opacity: 0.5;
}
#child {
width: 20px;
height: 20px;
position: absolute;
top: 10px;
right: 10px;
z-index: 2;
background-color: #FFF;
border-radius: 2px;
cursor: pointer;
}
#child:hover {
opacity: 0.5;
}
#parent p {
width: 100%;
position: absolute;
bottom: 0px;
text-align: center;
color: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<body ng-app ng-controller="TestController">
<div id="parent" ng-click="parentClick()">
<div id="child" ng-click="childClick($event)"></div>
<!-- ^^^^^^^ -->
<p ng-bind="elem"></p>
</div>
<div>
<p style="text-align:center" ng-bind="childElem"></p>
</div>
</body>
also you can use this as it use do the same.
<div id="child" ng-click="childClick();$event.stopPropagation();"></div>
Even if Pieter Willaert's answer is much more beautiful i updated your fiddle with a simple boolean check:
http://jsfiddle.net/qu86oxzc/6/
function TestController($scope) {
$scope.boolean = false;
$scope.parentClick = function () {
if (!$scope.boolean) $scope.elem = 'Parent';
$scope.toggleBoolean();
}
var i = 1;
$scope.childClick = function () {
$scope.boolean = true;
$scope.elem = 'Child';
$scope.childElem = 'Child event triggered x' + i;
i++;
}
$scope.toggleBoolean = function () {
$scope.boolean = !$scope.boolean;
}
}
You can also try $event.stopPropagation();. write it after the child function. It working like a preventdefault.
<body ng-app ng-controller="TestController">
<div id="parent" ng-click="parentClick()">
<div id="child" ng-click="childClick();$event.stopPropagation();"></div>
<p ng-bind="elem"></p>
</div>
<div><p style="text-align:center" ng-bind="childElem"></p></div>
</body>

Creating and showing div's with javascript

I am trying to create a list of friends and to do this I will need to create a div for each one. The code I tried hasn't worked.
Relevant JavaScript (Now at bottom of page):
document.getElementById("name").innerHTML = user;
document.getElementById("profilePic").src = "users/" + user + "/profilePic.jpg";
var friends = ["Test"];
var friendArea = document.getElementById("friendsDiv");
for (i=0; i < friends.length; i++) {
var friendDiv = document.createElement("div");
friendDiv.setAttribute("class", "friend");
var friendImage = document.createElement("img");
friendImage.setAttribute("class", "friendImage");
friendImage.setAttribute("src", "users/" + friends[i] + "/profilePic.jpg");
friendDiv.appendChild(friendImage);
friendArea.appendChild(friendDiv);
}
Relevant CSS:
.friends {
width: 100%;
height: 90%;
overflow-x: hidden;
overflow-y: auto;
}
.tools {
width: 100%;
height: 10%;
box-shadow: 0px 0px 3px 1px #898989;
}
.friend {
width: 100%;
height: 20%;
padding: 1%;
}
.friendImage {
height: 80%;
width: auto;
border: medium #CCCCCC solid;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
}
The HTML isn't really important but I'll include it anyway.
<div class="window">
<div class="rightCorner">
<img src="images/pPicTemp.png" id="profilePic">
</div>
<div class="holder" id="profileData">
<span id="name"></span>
</div>
<div class="sideBar">
<div class="friends" id="friendsDiv">
</div>
<div class="tools">
</div>
</div>
Is your script in a tag? Also is the document loaded when you attempt this? What does the console says? Is it working with no css? Also if photo path doesnt work there is no other content in the div did you try outputting something else?
You're not appending the friendImage to the friendDiv.
It should look like this:
var friends = ["Test"];
var friendArea = document.getElementById("friends");
for (i=0; i < friends.length; i++) {
var friendDiv = document.createElement("div");
friendDiv.setAttribute("class", "friend");
var friendImage = document.createElement("img");
friendImage.setAttribute("class", "friendImage");
friendImage.setAttribute("src", "users/" + friends[i] + "/profilePic.jpg");
friendDiv.appendChild(friendImage);
friendArea.appendChild(friendDiv);
}
Also, be sure to put this script at the bottom of your HTML <body></body> tag so that the HTML has loaded the entire document before the JavaScript attempts to get elements from the page.

Add CSS Class after HTML div using JQuery

I have this HTML
<div class="portItem"></div>
<div class="portItem"></div>
<div class="portItem"></div>
<div class="portItem"></div>
This CSS
.rectangle {
height: 250px;
width: 100%;
position: relative;
display: none;
background: #ffffff;
box-shadow: 1px 0px 20px black;
overflow-y: hidden;}
Here's the CSS for portItem, although not necessary (forms 4 green blocks next to each other)
.portItem {
height: 180px;
width: 250px;
position: relative;
display: inline-block;
background: #D0E182;
margin: 0 5px 5px 0;
And I'm trying to add the CSS rectangle after any of the portItems that I click on.
Here's the JQuery function I'm trying to use:
$(document).ready(function() {
$('.portItem').click(function() {
addDiv($(this));
});
});
function addDiv($ele) {
var $box = $('<div />' '.rectangle');
$box.insertAfter($ele);
}
The problem is with the var $box statement, I can't get it to work.
Thanks in advance!
You're missing a comma, and an object.
var $box = $('<div />', {'class':'rectangle'});
// -------------------^ ^ ^
// added comma-----| |___________________|---and object literal syntax
The quotes around class are needed to support older browsers. You could also use className instead.
var $box = $('<div />', {className:'rectangle'});
How about this:
var $box = $('<div/>').addClass('rectangle');
... or as simple as...
var $box = $('<div class="rectangle"/>');
Actually, I might consider preparing this item first-hand, then just cloning it. For example:
var $boxTemplate = $('<div class="rectangle">');
function addDiv($ele) {
$boxTemplate.clone().insertAfter($ele);
}
change the var $box line to:
var $box = $('<div class="rectangle" />');

Categories