How to use document.getElementById with jquery next siblings selector - javascript

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());});

Related

Getting divs by classes with querySelector() and exclude other class

I'm trying to simply get all of the first divs while exlcuding the second divs:
<div class="_5pcr userContentWrapper">
<div class="_5pcr userContentWrapper _4nef">
I searched and fout of that the querySelector function should be doing the job. However I tried it with multiple inputs, but all of those result in an empty list. If I use the DOM function getElementsByClass it works but then of course I got all divs, also the second ones that I don't want.
Here are the querySelector function calls I tried:
listOfPosterName = document.querySelectorAll('div._5pcr userContentWrapper:not(._4nef)');
listOfPosterName = document.querySelectorAll('DIV._5pcr userContentWrapper');
listOfPosterName = document.querySelectorAll('_5pcr userContentWrapper:not(_4nef)');
listOfPosterName = document.querySelectorAll('DIV.userContentWrapper:not(_4nef)');
I have even tried to just get the same result as with "getElementsByClass('_5pcr userContentWrapper')" with this:
listOfPosterName = document.querySelectorAll('_5pcr userContentWrapper');
That also did not work. I thought it's a problem because of the space between the classes, but I tested it also with a single class.
I really appreciate help!
Your problem is just putting too much spaces where unnecessary:
listOfPosterName = document.querySelectorAll('._5pcr.userContentWrapper:not(._4nef)');
You are not writing the selectors correctly.
When you want to select an element having multiple classes you would do:
document.querySelectorAll('.class1.class2.class3');
When you leave a space character in a selector - it becomes what is called a descendant selector. Example:
<div class="class1">
<p class="class2"></p>
</div>
In this case, class2 could be selected with a descendant selector:
document.querySelector('.class1 .class2');
Your fixed example could look like so:
<div class="_5pcr userContentWrapper">
<div class="_5pcr userContentWrapper _4nef">
document.querySelectorAll('._5pcr.userContentWrapper:not(._4nef)');
querySelector() works just fine, but you have to pass it the selector properly. Multiple classes should be concatenated together, not space separated like in the HTML.
document.querySelector("._5pcr.userContentWrapper").classList.add("selected");
.selected { background-color:yellow; }
<div class="_5pcr userContentWrapper">Me</div>
<div class="_5pcr userContentWrapper _4nef">Not Me</div>

jquery remove element if it occurs twice

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();

Jquery :contains selector without children

I need to do a function to change color (in this example) of dom element in javascript(jquery) but i have some trouble with :contains selector but i need to use because i don't have specific ID or class.
HTML :
<p id="title">John</p><!-- contain John must be red -->
<div id="description">John</div><!-- contain John must be red -->
<div id="element">
<p id="element1">John</p><!-- contain John must be red -->
<p id="element2">Anonymous</p><!-- dont contain John dont change color -->
</div>
ID in this code just to show you my problem.
Js :
$("div:contains('John'), p:contains('John')").css("color", "red");
Problem :
This script make unwanted changes (#element2)
I already check : Jquery doc but to simple dom in this example .
Testable example here : JSFIDDLE
Try to use exclude the div with other elements,
$("div:contains('John'):not(:has(*)), p:contains('John')").css("color", "red");
If your html have chances of containing elements like this,
<div id="description">John<p>test</p></div>
Then ultimately you have to go along with #TrueBlueAussie's answer.
DEMO
You could create your own filter that removes children elements and checks the textNodes of the current element only.
As the string you're trying to match is present in the comments as well, any use of innerHTML is out, so textContent is used.
$("#bug").on('click', function () {
$("div, p").filter(function() {
var clone = this.cloneNode(true);
while (clone.firstElementChild) {
clone.removeChild(clone.firstElementChild);
}
return clone.textContent.indexOf('John') != -1;
}).css("color", "red");
});
FIDDLE

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 });

jquery remove removing from another element

According to here, jquery's remove function should work like so..
$('div').remove('selector');
Which I'm trying in this example.
HTML:
<div class="wrapper">
<p class="unwanted">This should be removed</p>
<p class="retained">This will remain</p>
</div>​
JavaScript:
jQuery(document).ready(function($) {
$('div').remove('p.unwanted'); //not working
//$('p.unwanted').remove(); //this works
});
​
It's not working. What am I doing wrong?
You've misunderstood what the documentation is saying. It's not looking for elements that are descendants of the matched elements that match the selector, it's simply filtering down the set of already matched elements to those that match the selector, and then removing them.
If you have this HTML:
<div class="wanted">Some text</div>
<div class="wanted">Some more text</div>
<div class="unwanted">Some unwanted text</div>
and then executed this jQuery:
$('div').remove('.unwanted');
then it would only remove that third <div> (the one with the unwanted class on it), because it first selects all <div> elements, and then only removes those that match the selector.
Example jsFiddle
You're trying to remove something that is both div and p.unwanted. The filter in remove() is applied to the current set of nodes, which in this case is all div elements.
Use the children set instead:
$('div').children().remove('p.unwanted');
You should use the following:
$('p').remove('.unwanted');
Argument in remove works as a filter. So here, you first select all <p> elements and then remove only those which have class unwanted.
DEMO: http://jsfiddle.net/qwXSw/1/
try this
$(document).ready(function() {
$('div').find('p.unwanted').attr('class', '');
});

Categories