using jquery remove part of a cloned element - javascript

having a difficult time removing a div inside of a cloned element. run the snippet and notice the do not clone me part gets appended even though it is removed.
let myhtml = `<div style="border: 1px solid black;" class="mycontainer">
clone me
<div class="noClone">
do not clone me
</div>
<button class="clonebtn"> clone it </button>
</div>`
$(document).ready(function() {
let content = $(myhtml);
$('.row').append(content);
$('.row').on('click', '.clonebtn', function() {
let container = $(this).closest('.mycontainer');
let clonedContainer = container.clone();
clonedContainer.remove('.noClone');
$('.row').append(clonedContainer);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
</div>
</div>
or run the fiddle here https://jsfiddle.net/k6jz9xe2/3/

You need to use .find() to find all elements inside the parent div with a class of noClone to remove.
$(selector).remove(anotherselector) in jQuery only removes any elements matching anotherselector from the Array returned by selector. The selector given to the remove() function is only applied to the elements contained in the jQuery collection not to the children of those elements. It is analogous to $(selector).filter(anotherselector).remove().
Consider the following HTML and jQuery code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
Foo
<div id="bar">Bar</div>
</div>
<script>
$('#foo').remove('#bar');
</script>
You may expect that the div with the id "bar" inside the div with the id "foo" will be removed, but this is not the case. Why? The $('#foo') selector returns an Array with just one item: the div with the id of "foo". jQuery attempts to filter through the Array and find an element matching the $('#bar') selector. No element is found and nothing will happen.
The following selector, however, will remove the div with the id of "bar".
$('div').remove('#bar');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
Foo
<div id="bar">Bar</div>
</div>
<script>
$('div').remove('#bar');
</script>
The $('div') selector returns an Array with all the divs on the page. jQuery filters through all of the divs to find an div matching the $('#bar') selector (having an id of "bar"). Having found one, it removes it.
let myhtml = `<div style="border: 1px solid black;" class="mycontainer">
clone me
<div class="noClone">
do not clone me
</div>
<button class="clonebtn"> clone it </button>
</div>`;
$(document).ready(function() {
let content = $(myhtml);
$('.row').append(content);
$('.row').on('click', '.clonebtn', function() {
let container = $(this).closest('.mycontainer');
let clonedContainer = container.clone();
clonedContainer.find('.noClone').remove();
$('.row').append(clonedContainer);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
</div>
</div>

let myhtml = `<div style="border: 1px solid black;" class="mycontainer">
clone me
<div class="noClone">
do not clone me
</div>
<button class="clonebtn"> clone it </button>
</div>`
$(document).ready(function() {
let content = $(myhtml);
$('.row').append(content);
$('.row').on('click', '.clonebtn', function() {
let container = $(this).closest('.mycontainer');
let clonedContainer = container.clone();
clonedContainer.find('.noClone').remove();
$('.row').append(clonedContainer);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
</div>
</div>

Related

How to add event listeners to div elements?

I want to add an event listener to each of the div elements with the class "box" here:
<div class="gameBox">
<div class="msgs">
<p class="msg">Click in a box to play. Crosses start.</p>
</div>
<div class="gameTable">
<div class="box" id="0"></div>
<div class="box" id="1"></div>
<div class="box" id="2"></div>
<div class="box" id="3"></div>
<div class="box" id="4"></div>
<div class="box" id="5"></div>
<div class="box" id="6"></div>
<div class="box" id="7"></div>
<div class="box" id="8"></div>
</div>
<div class="reset">Reset</div>
</div>
let elementsArray = document.querySelectorAll(".box");
elementsArray.forEach(function(div) {
div.addEventListener("click", function() {
alert("AA");
});
});
This is the JavaScript I have used to do this, however it does not return anything. I think the issue may be that the div element is inside another div element because the code works when I take it out of the rest of my program. Please teach me the path to redemtion.
It looks like your code is correct. One thing you can try is to make sure that the script is being executed after the elements are added to the page. You can do this by placing your script at the end of the <body> element, just before the closing </body> tag.
Here's an example:
<body>
...
<div class="gameBox">
...
</div>
<script>
let elementsArray = document.querySelectorAll(".box");
elementsArray.forEach(function(div) {
div.addEventListener("click", function() {
alert("AA");
});
});
</script>
</body>
This ensures that the elements with the box class are added to the page before your script runs.
Another thing you can try is to add a debug statement to your code to see if the elementsArray variable is actually getting populated with the elements you expect. You can do this by adding a console.log statement, like this:
let elementsArray = document.querySelectorAll(".box");
console.log(elementsArray);
elementsArray.forEach(function(div) {
div.addEventListener("click", function() {
alert("AA");
});
});
This will print the elementsArray variable to the JavaScript console, which you can access in your web browser. This will allow you to verify that the elementsArray variable contains the elements you expect.
One solution is to add an event listener to the window object instead, and check if the clicked element is one of these .box elements.
window.addEventListener("click", (e) => {
if (e.target.classList.contains("box")) {
console.log(e.target.id);
}
});

How to ignore hidden objects on match on HTML? [duplicate]

This question already has answers here:
Using jQuery, how do you find only visible elements and leave hidden elements alone?
(4 answers)
Closed 3 years ago.
I'm trying to match visible object's text but ignore not visible ones. By the way I need HTML code.
Here is my codepen.
Here is my HTML:
<div class="main">
<div class="a">Hello</div>
<div class="hid">Hello</div>
<div class="b">Hello</div>
<div class="hid2">Hello</div>
<div class="c">Hello</div>
<div class="hid3">Hello</div>
<div class="hid4">Hello</div>
</div>
My CSS:
.hid, .hid2, .hid3, .hid4{
display: none;
}
My JavaScript:
var regEx = /Hello/g;
var main = $('.main').html();
var matches = main.match(regEx);
console.log(matches);
Actually I want to exclude invisible elements without removing them from page. I want these HTML codes at the result:
<div class="a">Hello</div>
<div class="b">Hello</div>
<div class="c">Hello</div>
I don't want to remove the hidden objects because I'll use them interactively. I just want to exclude them from match. We can use jQuery.
Thank you from now.
You can try with :visible selector like $('.main div:visible')
var visible = $('.main div:visible').map((_,i) => i.outerHTML).get();
console.log(visible);
.hid, .hid2, .hid3, .hid4{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<div class="a">Hello</div>
<div class="hid">Hello</div>
<div class="b">Hello</div>
<div class="hid2">Hello</div>
<div class="c">Hello</div>
<div class="hid3">Hello</div>
<div class="hid4">Hello</div>
</div>
You can use the :visible selector to find all the divs under .main which are not hidden, and then output their outerHTML value if they match the regex:
var regEx = /Hello/g;
var visible = $('.main div:visible');
visible.each(function () {
if ($(this).text().match(regEx)) {
console.log(this.outerHTML)
}
});
.hid, .hid2, .hid3, .hid4{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<div class="a">Hello</div>
<div class="hid">Hello</div>
<div class="b">Hllo</div>
<div class="hid2">Hello</div>
<div class="c">Hello</div>
<div class="hid3">Hello</div>
<div class="hid4">Hello</div>
</div>
var regEx = /Hello/g;
$(".main div:visible").each(function(val, html){
let inerHTML = $(this).html();
console.log(inerHTML.match(regEx))
})

Is there any inbuild function in javascript to select last element with using class selector or element selector?

similar type of question is already asked link.but my question is bit diffrent.
in my program frequently occur new element with using dom. here my question is
is there any built in function in javascript that i can select last element frequently?
here is an example
var para = document.createElement("div");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
given program append div element frequently and also i want to select div element frequently. similar with a class
thankyou in advance
Use querySelectorAll and pass the class selector. Then target the last element and do whatever
let getAllElem = document.querySelectorAll('.test');
getAllElem[getAllElem.length - 1].classList.add('green')
.green {
color: green
}
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
<div class="test">6</div>
no there is not any built in function in java script but u should try below logic and use it with jquery like $(last_selector(".lastclass")).click(); for select last class and $(last_selector("div")).click(); for elect last element
function last_selector(select){
if(select[0]=="."){
var allSelect = document.getElementsByClassName(select.slice(1));
}
else{
var allSelect = document.getElementsByTagName(select);
}
return allSelect[allSelect.length-1];
}
console.log(last_selector("div"))
console.log(last_selector(".last"))
<div>hello</div>
<div>hello</div>
<div class="last">last class</div>
<div>last element</div>
It will give last span text inside every Div using $(elementName).children("span:last").text()
$(document).ready(function(){
console.log($('div').children("span:last").text())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="time">2016</span><br>
<span class="time">2017</span><br>
<span class="time">2018</span><br>
<span class="time">2019</span><br>
<span class="time">2020</span><br>
<span class="time">2021</span><br>
<span class="time">2022</span><br>
<span class="time">2023</span><br>
<span class="time">2024</span> <br>
</div>

JQuery unable to find ID assigned to a newly appended HTML string

I have a HTML string, I've assigned the div with the class parent an id of myid (in the HTML string). I then append this HTML string to an element with id main. Using the browsers inspect tool I can see that the id has been infact assigned, but for some reason JQuery doesn't know about the newly assigned id.
var html = `
<div class="parent">
<div id="content" >
</div>
<div>`
var newHtml = $(html);
newHtml.find('.parent').attr('id','myid');
$('#main').append(newHtml);
console.log($('.parent').attr('id')); // Logged as undefined.
The method $.fn.find() targets the descendant elements where as $.fn.filter() target the element at same level. As per your HTML .parent is at top level, hence you need to use $.fn.filter() while setting the ID of DIV element.
var html = `<div class="parent">
<div id="content" >
</div>
<div>`
var newHtml = $(html);
newHtml.filter('.parent').attr('id','myid');
$('#main').append(newHtml);
console.log($('.parent').attr('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="main"></div>
OR, You don't need to use $.fn.find() at all. Just directly use .attr()
var html = `<div class="parent">
<div id="content" >
</div>
<div>`
var newHtml = $(html);
newHtml.attr('id','myid');
$('#main').append(newHtml);
console.log($('.parent').attr('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="main"></div>
You should use find method in combination with andSelf() method.
andSelf() method add the previous set of elements on the stack to the current set.
Read more here.
var html = `<div class="parent">
<div id="content" >
</div>
<div>`;
var newHtml = $(html);
newHtml.find('.parent').andSelf().attr('id','myid');
$('#main').append(newHtml);
console.log($('.parent').attr('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="main"></div>

If I hover over an element, how can I select all sibling elements before it and including it, in jQuery?

I have the html:
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
I have the following javascript:
$(document).on('mouseover', 'div', function() {
var elements = ''; // <-- What should I put here?
});
If I'm hovering over div#three I want the variable elements to be a collection of div#one, and div#two, div#three
How can I achieve this in jQuery?
You can do:
var elements = $(this).prevAll("div").addBack()

Categories

Resources