How to remove element using jquery - javascript

I have div which contains:
<div id="div1">
<span class="input-group-addon">Span1</span>
<span class="input-group-addon">Span2</span>
<span class="input-group-addon">Span3</span>
<span class="input-group-addon npsButton"><a target='_blank' href='nps.html'>Link</a></span>
</div>
I tried to remove the last span .npsButton by using: $("#div1").remove("span.npsButton"); but it's not working. When I check by the console $("#div1span.npsButton"), it returned []. Can anyone show me how can I remove this span

Use descendant selector
$('#div1 .npsButton').remove()
// ^ Note the space here
$("#div1span.npsButton") will select the element having ID as div1span and class npsButton. As there is no element that satisfies this selector, it'll return empty array.
To remove all elements in DOM having that class,
$('.npsButton').remove();

Use
$("span.npsButton").remove();

Beside selecting using class or id there are few other ways you can select the last child
:last-child Selector
.last()
:nth-last-child()
In the following snippet I am using :last-child which will select all element that is last child of the parent
$( "div#div1 span:last-child" ).remove()
Working example

Try like this
$( "#div1 span" ).last().hide();

Related

.closest() returns undefined

I have the following list:
<div id="saved">
<ul class="list-group" style="display: block;">
<li class="marked list-group-item">box-shadow:<span class="marked_text">0px 0px rgb(200,200,200)</span>;<a class="pull-right multiple-shadows checkbox-active">Click</a>
</li>
</ul>
</div>
Now i want to store the text that is inside inside a variable.
I have written the following code:
$("body").on("click", "#saved ul li > a.multiple-shadows", function () {
$(this).toggleClass("checkbox-active");
var roll = $(this).closest("span").text();
console.log(roll);
});
The problem is that with .text() i get an empty value and with .html() i get undefined.Any ideas?
$.closest() gets the parent (https://api.jquery.com/closest/). What you need is $(this).siblings("span"). Also try to limit the number of selectors in jQuery. $('a.multiple-shadows') is more than enough.
EDIT: if you have more than one span siblings, to get the first one, use $(this).siblings("span").first()
closest finds the closest ancestor of an element. the span is a sibling of your a tag, so closest is correct to return undefined. your a is inside of an li, which is inside of a ul, which is inside of a div, so those are the only elements that closest will return anything for.
Since your span come before the a tag, you simple can use the .prev() function.
$(this).toggleClass("checkbox-active");
var roll = $(this).prev().text();
console.log(roll);
Fiddle: http://jsfiddle.net/hp9or7pf/
.closest "matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree" (https://api.jquery.com/closest/). Therefore, .closest will not match any siblings but ancestors. Instead, you can use .prev().
$("#saved").on("click", ".multiple-shadows",function(){
$(this).toggleClass("checkbox-active");
var roll=$(this).prev().text();
alert(roll);
});

jQuery.next() returns empty object

I'm trying to get the next div after an image:
<a rel="nofollow" href="http://localhost:8046/file.htm" class="imgbox">
<img src="http://www.domain.tld/fm/912/image.png" class="" id="img-1303122" style="max-width:560px;" width="700" border="0" alt="title="/>
</a>
<div id="lic-img-1303122" class="licence-wrapper" style="display:none;">
<div class="licence-spacer"></div>
<div class="licence">© copyright<br /></div>
</div>
My jQuery code is the following:
console.log($("#img-1303122").nextAll(".licence-wrapper"));
Object { length: 0, prevObject: Object, context: HTMLDocument → JSUmstellung, selector: "#img-1303122.nextAll(.licence-wrapper)" }
So, why do I get no result? I already tried .next(), .closest() and .siblings() and none of them worked.
try :-
console.log($("#img-1303122").parent().nextAll(".licence-wrapper"));
Demo
Try this : you are trying to find next element directly to image, but actually div is present next to anchor tag. So get parent anchor tag with class="imgbox" and then .nextAll
console.log($("#img-1303122").closest('.imgbox').nextAll(".licence-wrapper").length);
#img-1303122 doesn't have other divs close by, probably you meant lic-img-1303122, next looks only for siblings, from the docs:
Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
.nextAll() Gets all following siblings of each element in the set of matched elements, optionally filtered by a selector.
So you need to try this:
$("#img-1303122").parent().nextAll(".licence-wrapper")
Hey you can also get all div by this
alert($("#img-1303122").parent().parent().find(".licence-wrapper").length);
Demo

How to find elements without a class in Jquery?

I have the following html
<div class="one">One<div>
<div class="two">two<div>
<div >three<div>
<div >four<div>
<div class="three">five<div>
How would I find the div elements which don't have a class attribute? ie three and four?
You can use :not selector
$('div:not([class])');
here is API
And a simple Fiddle
Use :not selector to filter
$('div:not([class])');
Combine the :not() selector with the attribute present selector [class].
$("div:not([class])")
jsFiddle.
Another option is to use .not() with Has Attribute Selector
$('div').not('[class]')
There are different ways to do it. You could use .children() to get the list and then index into that. Or you could look up the second element and use .next() to get its sibling.
Assuming you're not wanting to select all the dividers which have no classes, you can use nth-child to select specific ones if you know exactly where they are within a container. This will select your class-less dividers:
$('div:nth-child(3)') // Selects the third divider
$('div:nth-child(4)') // Selects the fourth divider
$('div:nth-child(3), div:nth-child(4)') // Selects both
JSFiddle example.
Alternatively you can select using .prev() and .next():
$('div.two').next() // Selects the divider after div class="two"
$('div.three').prev() // Selects the divider before div class="three"

How to select an element by ID using jQuery

I am trying to use the following jQuery code to add a div with class col_box inside the col_left div:
$('#col_left').add('div').addClass('col_box');
My DOM tree looks like this:
<div id="header">Header</div>
<div class="col_container">
<div id="col_left">
<div class="col_box">A</div>
<div class="col_box">B</div>
</div>
</div>
However the jQuery code isn't working. It adds the class col_box to every element on the page.
$('#col_left').add('div') is adding all <div> elements to the original selection. Try using $('#col_left').append('<div class="col_box"></div>') instead (or .prepend).
$('#col_left').add('div') means the same as $('#col_left, div'). i.e. "The element with the id 'col_left' and all div elements.
If you want to select the divs that are children of col_left, just use a child combinator.
$('#col_left > div').addClass('col_box')
.add() adds a selector to the selection, it doesn't create or add elements.
$('#col_left') means *select element id col_left*
.add('div') means add all divs of the page the the selection
So at this point you've selected #col_left and all the divs.
.addClass('col_box') means *add the class col_box to all elements of the selection*.
Here is how to create a div and add it to #col_left:
$('<div></div>').addClass('col_box').appendTo('#col_left');
Or:
$('<div class="col_box"></div>').appendTo('#col_left');
you can use
.append appends after the matched target
$('#col_left').append(
$("<div/>",{class:'col_box'}).html("div added")
);
here is the fiddle http://jsfiddle.net/R65cn/4/

Jquery find all except

I have following HTML:
<div id="123" class="test">
<div class="testMessage">Foo</div>
<div><div class="testDate">2010</div></div>
<div id="127" class="test">
<div class="testMessage">Bar</div>
<div><div class="testDate">2011</div></div>
</div>
</div>
And I have following JS/jQuery code:
$(".test").find(".testDate").val("cool 2010");
How to change JS/jQuery to find "testDate" class element except in children "test" class block without using children?
P.S. I know only about class name and I don't know how many divs can be nested.
Update
Its probably the weirdest selector I've ever written:
$("div.test").not(':has(> .test)').siblings().find('.testDate').text('cool 2010');
Demo: http://jsfiddle.net/mrchief/6cbdu/3/
Explanation:
$("div.test") // finds both the test divs
.not(':has(> .test)') // finds the inner test div
.siblings() // get all other divs except the inner test div
Try this and also div elements do not have a value property, use html() method to set the inner html or text()
$("div.test :not(.test)").find(".testDate").html("cool 2010");
If you can modify your main div id to "_123", you can straight away use the id selector like this
$("#_123 > div.testDate").html("cool 2010");
I think the not() selector might help. You can learn more about it here: http://jsperf.com/jquery-css3-not-vs-not
Anytime you try to select $('.test'), it will grab all elements with a class='test'. You need to start at the outermost body tag:
$('body').children('.test').children(':not(.test)').find('.testDate').text('cool 2010');

Categories

Resources