jquery remove element if it occurs twice - javascript

I have something like this in my html:
<div class="onlyContent">
<!-- some more stuff here -->
</div>
<div class="onlyContent">
<!-- some more stuff here -->
</div>
Now, with jQuery I want to remove the 2nd occurence of the class onlyContent HTML from the dom.
The final result should be this:
<div class="onlyContent">
<!-- some more stuff here -->
</div>
I figured out that you can somehow use the nth-child-selector, but trying to access it this way didn't do it for me
$('.onlyContent:nth-child(2)').remove();

You can use :eq(1) for targetting second element in matched set:
$('.onlyContent:eq(1)').remove();
If the number of elements more than two, then you should use :not(:first) or :gt(0):
$('.onlyContent:not(:first)').remove();
or
$('.onlyContent:gt(0)').remove();

use below code . use jQuery :eq() selector.
Select the element at index n within the matched set.
check DEMO
$('.onlyContent:eq(1)').remove();

you can try this
$('.onlyContent:gt(0)').remove();

You can try this -
$('.onlyContent:gt(0)').remove();
It will remove all the duplicates. Only the first one will be present.

You can use .slice for this.
$(".onlyContent").slice(1).remove();
Nice and simple, no fuss. Working example.
From the .slice documentation:
Reduce the set of matched elements to a subset specified by a range of
indices
You can find more here.

Use .length property to check the numbers of selected elements on the page and if its value is greater than 1 then remove the elements other than first...
if($('.onlyContent').length > 1) {
$('.onlyContent:gt(0)').remove();
}

you can try
$(".onlyContent").not(':first').remove();

Related

Getting element with querySelectorAll() that starts with a certain string but does NOT end with a certain string

The page I'm working on has many elements of similar elements, for all of them the id starts with the string "text_d" but half has an additional "_description" at the end. I want to add an event listener to all of these that do not end with description.
I know the startsWith and endsWith notations (^=,$=) and I've heard about not(), so I tried this:
elements = document.querySelectorAll('*[id^="text_d"]','*:not(*[id$="description"])');
But to no avail. Is there a way to do this? Or do I have to resort to selecting them all and then sort out the unwanted ones out in the event listener function with something like
if(!element.id.endWith("_description")){...}
You need to chain :not selector to first argument:
elements = document.querySelectorAll('[id^=text_d]:not([id*=description])');
elements.forEach(e=>e.style.color="red")
<div id="text_d">1</div>
<div id="text_d">2</div>
<div id="text_d_description">not</div>
And your 2nd approach was good, its just not endwith, its endsWith:
elements = document.querySelectorAll('[id^=text_d]');
elements.forEach(e=> !e.id.endsWith("_description") ? e.style.color="red" : null)
<div id="text_d">1</div>
<div id="text_d">2</div>
<div id="text_d_description">not</div>
When you get console error * is not a function, always go check that * something.

Select all divs with specified string

$("#slide") code formating i've got something like this, i want my function to select all id's starting from slide, slide1, slide2 etc.
In bash there is slide*, which does that job, is there anything like this in jquery?
Thank you for your help
You can use the attribute selector in combination with :not() to select slide* and exclude #slide2
$('[id^="slide"]:not("#slide2")').css('color','red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slide">slide</div>
<div id="slide1">slide1</div>
<div id="slide2">slide2</div>
<div id="slide3">slide3</div>
<div id="slide4">slide4</div>
yes $('[id^="slide"]'). This says: any Node that has an id-attribute that starts with "slide";
But your actual mistake is to use IDs in this place. Enumerated whatever hint that you're actually dealing with a list of some kind. In this case this list would better be represented by a (css) class instead of a set of IDs.
*Enumerated whatever means: enumerated variables, properties, methods, functions, IDs or classes, ... In each of these cases you should determine the nature of this group and reconsider your structure.
jQuery is not necessary
In this case it's better to use classes, or element tags, in place of IDs
Given what you have, you could easily look at the start of the id attribute for "slide" and collect all except slide2 using the :not() selector filter function.
let slides = document.querySelectorAll('[id^="slide"]:not(#slide2)');
console.log(slides);
slides.forEach(s=>s.innerHTML+=' - matched');
<div id="slid1">not slide</div>
<div id="slide">slide</div>
<div id="slide1">slide1</div>
<div id="slide2">slide2</div>
<div id="slide3">slide3</div>
<div id="slid2">not slide</div>
$('[id^="slide"]').not('#slide2');
Is what you are looking for as a css selector.

selecting on dom parser using jquery with relevant class div12 div31 all at one time

Thanks for reading my post..
Just consider the below scenario of html architecture.
<div class="wrapper">
<div class="doubt-123232" id="value"></div>
<div class="question></div>
<div class="doubt-232323" id="query"></div>
</div>
In the above DOM if you need to select the class starting with doubt-***** (which include doubt-123232, doubt-232323) all at a time and do processing using jQuery.
We can select each class one by one and do processing, but in my page I have lot like this . I cant do it for each class to select and do processing then it became a trivial process.
Is there way to select the similar class or id all at time for processing in jQuery?
Thanks.
Yes, you can do this using Attribute Starts With Selector:
var divs = $('div[class^="doubt-"]');
You can use:
var items = $('div[class^=doubt]');
This is known as the "starts with" selector.
Alternatively you could use:
var items = $('div[class*=doubt]');
which is the "contains" selector.
Note that in this case, doubt is one word. If there are multiple words with spaces in between, you should put quotes around them. It is not required to quote single words.
See here for documentation on the "starts with" selector.
You can use Attribute Starts With Selector [name^="value"]
var divs = $('div[class^="doubt-"]');
selecting them all:
var doubts= $('[class^="doubt-"]');
then you access them:
doubts.each(function(index){
this. ... // and so on
});
Try somthing like this:
$("[class^=doubt-]").each(function(){ //do some staff });

How to use document.getElementById with jquery next siblings selector

I want to remove some silblings. I tried as given below.
But not working. why? And how to solve it?
<div>
<div id="idx1">child1 </div>
<div id="idx2">child2</div>
<div id="idx3">child3</div>
...
<div id="/a/b/c">This should be last child</div>
<div id="idx4">Remove it.</div>
<div id="idx5">Remove it.</div>
<div id="idx6">Remove it.</div>
...
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
// Since the id contains special chars,
// javascript method has been used to get the element.
lastChildObj = jQuery(document.getElementById('a/b/c'));
// I don't know how to remove the childs after lastChildObj.
// I tried as given below.
lastChildObj.filter('~').remove();
There are two key steps to this.
Select the elements to remove
Remove them
Step 1 can be broken down into two parts, obtaining a reference to the last element to keep, then getting a list of all of its siblings that come after it. Step 2 just uses the .remove() function.
$(document.getElementById('/a/b/c')).nextAll().remove();
You can still use jquery for your selector but you need to escape the id like so :
$("#\\/a\\/b\\/c")
Then you just need to select any following divs like this :
$("#\\/a\\/b\\/c").nextAll().remove();
http://jsfiddle.net/8mMJq/
Further informations about special characters in selectors : http://api.jquery.com/category/selectors/
This should work for you:
var base = document.getElementById('/a/b/c');
while(base.nextSibling){ // While the element has siblings
base.parentElement.removeChild(base.nextSibling); // remove the siblings from the parent element.
}
Working example
You can also make it slightly more efficient:
var base = document.getElementById('/a/b/c');
while(base.parentElement.removeChild(base.nextSibling))ā€‹ // Remove the nextSiblings while they exist.
Example
Try this :
$("#\\/a\\/b\\/c").nextAll().remove();
JsFiddle : http://jsfiddle.net/QcvWQ/
First of all change id from "/a/b/c" to ie "abc" and then run following
$("#abc").nextAll().each(function () { $(this).remove());});

How to clear all <div>sā€™ contents inside a parent <div>?

I have a div <div id="masterdiv"> which has several child <div>s.
Example:
<div id="masterdiv">
<div id="childdiv1" />
<div id="childdiv2" />
<div id="childdiv3" />
</div>
How to clear the contents of all child <div>s inside the master <div> using jQuery?
jQuery's empty() function does just that:
$('#masterdiv').empty();
clears the master div.
$('#masterdiv div').empty();
clears all the child divs, but leaves the master intact.
jQuery('#masterdiv div').html('');
Use jQuery's CSS selector syntax to select all div elements inside the element with id masterdiv. Then call empty() to clear the contents.
$('#masterdiv div').empty();
Using text('') or html('') will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.
I know this is a jQuery related question, but I believe someone might get here expecting a pure Javascript solution. So, if you were trying to do this using js, you could use the innerHTML property and set it to an empty string.
document.getElementById('masterdiv').innerHTML = '';
jQuery recommend you use ".empty()",".remove()",".detach()"
if you needed delete all element in element, use this code :
$('#target_id').empty();
if you needed delete all element, Use this code:
$('#target_id').remove();
i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED
ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/
If all the divs inside that masterdiv needs to be cleared, it this.
$('#masterdiv div').html('');
else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.
$('#masterdiv div').each(
function(element){
if(element.attr('id').substr(0, 8) == "childdiv")
{
element.html('');
}
}
);
The better way is :
$( ".masterdiv" ).empty();
$("#masterdiv div").text("");
$("#masterdiv > *").text("")
or
$("#masterdiv").children().text("")
$('#div_id').empty();
or
$('.div_class').empty();
Works Fine to remove contents inside a div
You can use .empty() function to clear all the child elements
$(document).ready(function () {
$("#button").click(function () {
//only the content inside of the element will be deleted
$("#masterdiv").empty();
});
});
To see the comparison between jquery .empty(), .hide(), .remove() and .detach() follow here http://www.voidtricks.com/jquery-empty-hide-remove-detach/
When you are appending data into div by id using any service or database, first try it empty, like this:
var json = jsonParse(data.d);
$('#divname').empty();
$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});
or
$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});
try them if it help.
$('.div_parent .div_child').empty();
$('#div_parent #div_child').empty();

Categories