add a class to specific element by javascript and not repeat - javascript

this is sample code explain what i want:
<div id="someId">
<div class="someClass"></div>
<div class="targetClass"></div>
</div>
<div id="someId">
<div class="someClass"></div>
<div class="targetClass"></div>
</div>
<div id="someId">
<div class="someClass"></div>
</div>
this code for jquery:
var $newDiv = $("<div/>")
.addClass("targetClass")
$(".someClass").append($newDiv);
result is add a TargetClass in div number 3 and repeat same class in first and second div.
question is how i add class in the last div and not repeat it in another div.

Judging by your code, you want new div as a sibling of your .someClass div rather than its child.
Simply replace this line
$(".someClass").append($newDiv);
by
$( "div[id]:not(:has(.targetClass))" ).append($newDiv); //will append new div to all those divs which doesn't have child element with targetclass
var $newDiv = $("<div/>").addClass("targetClass");
$( "div[id]:not(:has(.targetClass))" ).append($newDiv);
Demo

Using .last() will select the last element you are searching for.
jQuery(".someClass").last().append($newDiv);

If you mean to add div with targetClass to a div with someId if it donot exists, you can use the find() function:
if($('#someId').find('.someClass').length == 0) {
var $newDiv = $("<div/>")
.addClass("targetClass")
$("#someId").append($newDiv);
}

I suppose you have unique IDs for parent divs as someId is not valid if it is the actual ID applied on multiple elements, this makes the markup invalid.
Use .last().parent() to put the element as a sibling element as they share same parent:
var $newDiv = $("<div/>")
.addClass("targetClass").html('dynamic target element.')
$(".someClass").last().parent().append($newDiv);
div{border:solid 1px red; margin:10px 0 0 0;}
div div{border:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someId-1">
<div class="someClass">some</div>
<div class="targetClass">target</div>
</div>
<div id="someId-2">
<div class="someClass">some</div>
<div class="targetClass">target</div>
</div>
<div id="someId-3">
<div class="someClass">here after this elem should add</div>
</div>

Related

How to hide parent div if first child is empty

I want to hide class "aa" if the first div element is empty in class "ca". Please guide me
My sample code:
<div class="aa">
<div class="ca">
<div></div>
<div class="cb"></div>
<div class="cc"></div>
</div>
<div>
Appreciate your response!
You can use children(":first") to get first child of div as
$(document).ready(function(){
if($('.ca').children(":first").text() == ""){
$('.aa').hide();
}
});
$(document).ready(function(){
if($('.ca').children(":first").text() == ""){
$('.aa').hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="aa">
<div class="ca">
<div></div>
<div class="cb">A</div>
<div class="cc">B</div>
</div>
<div>
You can check to see if the first childNode of the .ca parent element has content, and then target .aa from there if it does not:
//If there is no content within the first div of the class="ca" div...
//choose between textContent and innerHTML below
//based on whether it is going to have any text or some HTML within (with possibly no text)
if (!document.querySelector('.ca').childNodes[0].innerHTML) {
//hide the class="aa" div
document.querySelector('.aa').style.display = 'none';
}

I can't handle to select the correct div (using Jquery)

$(document).ready(function() {
$(".myClass").click(function () {
$(".myClass", $(this)).first().scrollIntoView({behavior: "smooth",block: "start"});
});
});
.myClass {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class=myClass>I click on this div
</div>
<div class=otherClass>Some random text
</div>
<div>
<div class=otherClass>Some random text
</div>
<div>
<div class=myClass>I want to scroll to this div
</div>
Here is my problem, i have this pattern that repeats itself several times in my page. Div having the class "otherClass" are generated dynamically in variable quantity.
<div>
<div class=myClass>
</div>
</div>
<div>
<div class=otherClass>
</div>
</div>
<div>
<div class=otherClass>
</div>
</div>
<div>
<div class=myClass>
</div>
</div>
My goal is by clicking on a "myClass" div to scroll down the window (using scrollIntoView()) to the next div with the same class.
I added a click event on each "myClass" div but i can't manage to select the next one. I tried to add a context to my selector $(".myClass", $(this)) to search only after the clicked div but it doesn't work (always returning me the current div ?).
I also tried using next() to "move" to the next div but i'm struggling with the fact that there is an unknown numbers of "otherClass" div between them.
What am i doing wrong ?
Sorry if my explanation isn't clear and thank you for your help.
Up to your html structure .myClass doesn't have any next .myClass on its level .. See the next code
$('.myClass').on('click' , function(){
$(this)
.parent() // select the parent div
.nextAll('div:has(.myClass)') // select the next div which has .myClass in it
.first() // select just one div next
.find('.myClass') // find the .myClass in this div
.addClass('Next'); // add class to it
});
.Next{
background : red;
color : #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class=myClass>myClass</div>
</div>
<div>
<div class=otherClass>Other</div>
</div>
<div>
<div class=otherClass>Other</div>
</div>
<div>
<div class=myClass>myClass</div>
</div>
<div>
<div class=otherClass>Other</div>
</div>
<div>
<div class=otherClass>Other</div>
</div>
<div>
<div class=myClass>myClass</div>
</div>
Additional: if you need to reverse you'll need to use prevAll instead of nextAll and .last() instead of .first()
This will work no jQuery needed.
Here is the fiddle example: https://jsfiddle.net/e1xz74wj/
JS
let scrollToNext = 0;
const elements = document.querySelectorAll('.myClass');
document.getElementById('btn').addEventListener('click', () => {
++scrollToNext
if (scrollToNext < elements.length) {
elements[scrollToNext].scrollIntoView();
}
})
Explanation:
Increment the counter after clicking on the button to scroll to the desired element (finding element by specified className).
Each time a click occurs the counter is incremented by one hence the next element is selected. When the counter reaches the max amount of found elements it doesn't increment anymore.

Clone and append on click makes multiple elements and toggle not working

I am trying to clone and append elements. after i append i have added a toggle animation. on first click it works fine. after i am getting mutliple elements appended.
as well the animation not working.
here is the html:
<div class="parent hide">
<div class="header">
<h6>Header</h6>
</div>
<div class="content">
<p>paragraph content </p>
</div>
</div>
<div id="content">
</div>
<button>Add</button>
Js :
$('.parent').on('click', '.header', function () {
$(this).find('h6').toggleClass('name').end()
.siblings('.content').slideToggle();
});
$('button').on('click', function () {
var newParent = $('.parent').clone();
$('#content').append(newParent.removeClass('hide'));
});
JSfiddle
UPDATE:
I updated the cloning passing var newParent = $('.parent').clone(true); - animation works!
you should clone only the first element (or the last for that matter):
var newParent = $('.parent:first').clone(true);
EXAMPLE 1
Using .clone(true) seems to fix the animation. Another solution is targeting the parent on click and delegating .parent .header since the cloned .parent is being added to the DOM after the initial load:
$('#content ').on('click', '.parent .header', function () {
instead of
$('.parent').on('click', '.header', function () {
EXAMPLE 2
Cloning an elements means there will be two identical elements (having the same class aswell) afterwards.
Each time you click the button, all elements having the .parent class are cloned and appended to the #content
Regarding the animation:
The appended elements are not known to the DOM, so the .on('click') is not working.
Try to put a wrapper around your .parent elements and then use the following syntax:
HTML
<div class="wrapper">
<div class="parent hide">
<div class="header">
<h6>Header</h6>
</div>
<div class="content">
<p>paragraph content </p>
</div>
</div>
<div id="content">
</div>
</div>
<button>Add</button>
JS
$('.wrapper').on('click', '.parent .header', function(){ [...] });

Create clone of first two divs

I want to create clone of first two div of parent Div.
HTML Code
<div id="parent">
<div class="child"> <div class="child1>Content1...</div> </div>
<div class="child">Content2...</div>
<div class="child">Content3...</div>
<div class="child">Content4...</div>
<div class="child">Content5...</div>
<div class="child">Content6...</div>
</div>
Expected output
clone_object = '<div class="child"> <div class="child1>Content1...</div> </div>
<div class="child">Content2...</div>'
I tried below code but it will clone only first div of parent div.
clone_object = $("#parent").find("div:first").clone();
My question is how to clone first two div of parent div?
You need to use :lt selector.
Select all elements at an index less than index within the matched set.
$("#parent .child:lt(2)").clone();
or
$("#parent>div:lt(2)").clone();
Working Demo

Adding div before selected div

I have a bunch of divs one after the other.
<div class="betweenable">some content</div>
<div class="betweenable">other content</div>
<div class="betweenable">yet another</div>
When I click the last div, I want to insert the text new content in a div before it, so the final result will be
<div class="betweenable">some content</div>
<div class="betweenable">other content</div>
<div class="betweenable">new content</div>
<div class="betweenable">yet another</div>
I tried append but it's adding the new markup inside the select div at the top. I want it inserted outside the selected div and right before it. What should I use instead of this line
var newmarkup = '<div class="betweenable">new content</div>';
$(this).prepend();
You can try this
$('.betweenable').click(function(){
var newmarkup = '<div class="betweenable">new content</div>';
$(this).before(newmarkup);
});
Here's an example : http://jsfiddle.net/jomanlk/C4XyH/
you can use .before here is DEMO

Categories