jQuery: How to append something after one element? - javascript

DOM
<div id="a">
<div id="b"></div>
<div>
<p>Insert me after #b</p>
Requirement is insert p tag after '#b', and when the insert operation happened again, only replace the p tag instead of adding more.
Thanks for your help

This will insert it directly after #b, within #a, but if it already exists, then it wont insert it again.
$(document).ready(function(){
if ($('#newP').length == 0) {
$('#b').append('<p id="newP">Insert me after #b</p>')
}
});

Try this:
function insertP(html)
{
var a = $("#a");
var p = a.find("p")
if(p.length == 0)
{
p = $("<p></p>").appendTo(a);
}
p.html(html)
}

This function will remove an existing element then add a new element. If one does not exist it will simply add the element.
<body>
<script type="text/javascript">
$(document).ready(function() {
function addAfterB(pElement) {
if (!$('#b ~ p')) {
$(pElement).insertAfter('#b');
} else if ($('#b ~ p')) {
$('#b ~ p').remove();
$(pElement).insertAfter('#b')
}
}
addAfterB('<p>New Item 1</p>');
});
</script>
<div id="a">
<div id="b"></div>
<p>hello</p>
<div>

You can use $.after()...
<div id="a">
<div id="b"></div>
<div>
...
<script>
$("#b").after("<p>Insert me after #b</p>");
</script>

Related

jquery If statement based on a previous element

I want to hide an element if the previous element has a number less than 0.
https://jsfiddle.net/82bysjag/2/
$(document).on("click", function() {
$(".hide").each(function() {
var prevqty = $(".hide").prev().text();
if (prevqty < 0) {
$(this).hide();
} else {}
});
});
div {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
-2
</div>
<div class="hide">
Hide
</div>
<div>
1
</div>
<div class="hide">
Hide
</div>
Is there an error with my var prevqty?
Use $(this) and parseInt to
$(".hide").each(function() {
var prevqty = parseInt($(this).prev().text(), 10);
if (prevqty < 0) {
$(this).hide();
} else {}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>-2</div>
<div class="hide">Hide</div>
The problem is from prevqty. JavaScript is seing it as a string. Convert it to number first as follows;
var prevqty = $(".hide").prev().text();
prevqty =Number(prevqty );
Then you can compare

Event when a pair of elements are clicked

I have 5 elements with class .home and unique id's, and a button with class .btn1. When .home is clicked after .btn1 and vice versa, a function should be executed. I don't know what jQuery method i should use.
Try this :
<!DOCTYPE html>
<html>
<head>
<style>
.active {
background-color: skyblue;
}
</style>
</head>
<body>
<div class="home">I am Div1</div>
<div class="home">I am Div2</div>
<div class="home">I am Div3</div>
<div class="home">I am Div4</div>
<div class="home">I am Div5</div>
<button class="btn">Run</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var divReady = false;
var btnReady = false;
$(".btn").on("click",function(){
btnReady = true;
$(this).addClass("active");
if (divReady)
fun();
})
$("div").on("click",function(){
divReady = true;
$("div").removeClass("active");
$(this).addClass("active");
if (btnReady)
fun();
})
function fun() {
alert("I am working!")
$(".btn,div").removeClass("active");
btnReady = false;
divReady = false;
}
})
</script>
</body>
</html>
I don't think there's a specific jQuery trick for that.
Why not use classes to store state?
$(function() {
$(".home").click(function () {
$(this).addClass("active");
if ($(".btn1").hasClass("active")) {
console.log("Doing something");
}
});
$(".btn1").click(function () {
$(this).addClass("active");
if ($(".home").hasClass("active")) {
console.log("Doing something");
}
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
<button class = 'btn1' >Button</button>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
<div class = 'home'>
Home
</div>
<div>
Stuff
</div>
Simply count the times an event occured, and store the events. That can be easily done with an Array:
//create an array to store events
events=[];
//create a handler function
function handler(event){
//add the event to our array
events.push(event);
if(events.length==2){
//two events fired:
//first event:
a=events[0];
//second:
b=events[1];
//do whatever
}
}
//add an eventlistener that calls our handler and passes 'documentclick'
document.addEventListener("documentclick",function(){handler("click")});

Move one element into another element with remaining elements going to a third location

I am trying to swap elements with the moveButton function. When the user clicks on one of the images is moves the first one to the #good div and then any remaining will go into the #evil div. I have the if/else statement I thought would work.
<div id="character">
<script type="text/javascript">
function moveButton(elem){
if( $(elem).parent().attr("id") == "menu" ){
$(elem).detach().appendTo('#good');
}
else{
$(elem).detach().appendTo('#evil');
}
}
</script>
</div>
<div id="good">
</div>
<div id="evil">
</div>
<div id="menu">
<div class="character" onclick="moveButton(this)" data-name="Chomper">
<p>Chomper</p><p><img width="100" src="http://vignette2.wikia.nocookie.net/plantsvszombies/images/a/a3/Chomper1.png/revision/latest?cb=20090521220057" alt=" + Chomper + "></p><p>Hit Points: 3.55</p>
</div>
<div class="character" onclick="moveButton(this)" data-name="Kernel-pult">
<p>Kernel-pult</p><p><img width="100" src="http://vignette4.wikia.nocookie.net/plantsvszombies/images/c/c4/Kernel-pult1.png/revision/latest?cb=20090521220358" alt=" + Kernel-pult + "></p><p>Hit Points: 1.55</p>
</div>
</div>
Gate your if with a boolean like fiddle
<script type="text/javascript">
var good = false;
function moveButton(elem) {
if ($(elem).parent().attr("id") == "menu" && !good) {
$(elem).detach().appendTo('#good');
} else {
$(elem).detach().appendTo('#evil');
}
good = true;
}
</script>
To send all remaining caracters to evil use $("#menu").find(".character").detach().appendTo('#evil');
like in fiddle 2
<script type="text/javascript">
var good = false;
function moveButton(elem) {
if ($(elem).parent().attr("id") == "menu" && !good) {
$(elem).detach().appendTo('#good');
} else {
$(elem).detach().appendTo('#evil');
}
$("#menu").find(".character").detach().appendTo('#evil');
good = true;
}
</script>
Do not pass THIS to your function, it's already there in the scope. Also using detach() method, you are removing elements from DOM. Try the following...
function moveButton() {
if( $(this).parent().attr("id") == "menu" ) {
$(this).appendTo('#good');
} else {
$(this).appendTo('#evil');
}
}

Is element a descendant of some class?

<div class="blah">
<div id="hi">Hi</div>
<div id="hi2">
<p id="hi3">Hi3</p>
</div>
</div>
How to test with JavaScript if an element is child (or grandchild, or grandgrandchild, etc.) of an element of class blah? (said in another way : if an element is contained in an element of class blah).
Note: After some tests, .contains(...) seems not to be the solution.
Use matches:
elt.matches('.blah *')
See https://developer.mozilla.org/en-US/docs/Web/API/Element.matches. Check browser compatibility.
See also Test if a selector matches a given element.
Modernizr can help if the browser you are targeting requires a prefix:
var ms = Modernizr.prefixed("matchesSelector", HTMLElement.prototype, elt)
ms('.blah *')
See http://modernizr.com/docs/#prefixeddom.
Loop through parents, check each one.
function isContainedByClass(src,cls) {
while(src && src.tagName) {
if( src.classList.contains(cls)) return true;
// apply old-browser compatibility as needed
src = src.parentNode;
}
return false;
}
**check this out**
============================================================================
<!DOCTYPE html>
<html>
<head>
<style>
.a *
{
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//for checking if span with class c1 is children of class a element
if($('.a').children('span.c1').length > 0) {
console.log("Found");
}
//for checking if span with class c1 has parent element with class a
if($('.c1').parents('.a').length > 0) {
console.log("Found");
}
});
</script>
</head>
<body>
<div class="a">a
<div class="b">b
<div class="b1">b1</div>
<div class="b2">b2</div>
<span class="b3">b3</span>
</div>
<div class="c">c</div>
<span class="c1">c1</span>
<p class="c2">c2</p>
</div>
</body>
</html>

selecting un-id spans in a div

My markup is a div with 3 spans inside. How can I read the value of each span with jquery.
<div id="mod">
<span>first span<span>
<span>second span<span>
<span>third span<span>
</div>
function getVars(){
var span1 = ;
var span2 = ;
var span3 = ;
}
please try this
$('#mod').find('span').text();
$(document).ready(function(){
alert($("#mod span:first").text());//First span child only
alert($("#mod > span").text());// All span children
});
Note: Make sure to close your span "".
You can also use this
$(document).ready(function () {
alert($("#mod span:eq(0)").html());
});
Close the span tags <span> first </span> then it should work, all the answers
another variation
$(document).ready(function () {
alert($("#mod").children(":first").text());
});
<!DOCTYPE html>
<html>
<head>
<style>
span { color:#008; }
span.sogreen { color:green; font-weight: bolder; }
</style>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
<div>
<span>John,</span>
<span>Karl,</span>
<span>Brandon</span>
</div>
<div>
<span>Glen,</span>
<span>Tane,</span>
<span>Ralph</span>
</div>
<script>
$("div span:first-child")
.css("text-decoration", "underline")
.hover(function () {
$(this).addClass("sogreen");
}, function () {
$(this).removeClass("sogreen");
});
</script>
</body>
</html>

Categories