I know this has been extensively answered but alas I have had no luck with previous code.
So I want to remove all the span elements in this div element when the user onclicks a button.
THE HTML
<div id="sequence-label" class="scrollingDiv" style="visibility: hidden;">
<li>H :</li>
<span class="spanUnselected">T</span>
<span class="spanUnselected">F</span>
<span class="spanUnselected">G</span>
<span class="spanUnselected">Q</span>
<span class="spanUnselected">G</span>
</div>
**THE JS **
$('#sequence-remove-pdb').click(sequenceRemovePdb);
function sequenceRemovePdb() {
document.getElementById("sequence-label").style.visibility = "hidden";
workspaceSideChain();
var mySeq = document.getElementById("sequence-label");
}
Things I have tried
Tried to remove all the elements as children of sequence-label
mySeq.empty();
Tried to remove by class selected
mySeq.remove(".spanUnselected");
Tried to remove by firstChild Elements
while (mySeq.firstChild) {
mySeq.removeChild(mySeq.firstChild);
}
Tried to remove by childNodes also over how many elements are in sequence-label and still nothing.
Any ideas?
The Problem
You're mixing jQuery and vanilla javascript in a way that does not work.
Specifically, you're getting an element in vanilla javascript here:
var mySeq = document.getElementById("sequence-label");
Then you are trying to remove elements using jQuery:
mySeq.empty();
and
mySeq.remove(".spanUnselected");
The Solution
The solution is simple enough. Get the element as a jQuery object first, then your functions will work:
var mySeq = jQuery("#sequence-label");
// Then act on it with jQuery as you see fit.
mySeq.find('.spanUnselected').remove();
Also, be sure your event bindings take place inside of a document ready:
jQuery(function($) {
$('#sequence-remove-pdb').click(function() {sequenceRemovePdb;});
});
I might be missing the point but to completely empty the item this might work:
document.getElementById("sequence-label").innerHTML = "";
It will empty out all the children (actually everything) from inside the "sequence-label" element.
Try this code :
$('#sequence-remove-pdb').click(function(){
$('span.spanUnselected').remove();
});
HTML :
<div id="sequence-label" class="scrollingDiv">
<li>H :</li>
<span class="spanUnselected">T</span>
<span class="spanUnselected">F</span>
<span class="spanUnselected">G</span>
<span class="spanUnselected">Q</span>
<span class="spanUnselected">G</span>
</div>
The remove( expr ) method removes all matched elements from the DOM.
This does NOT remove them from the jQuery object, allowing you to use
the matched elements further.
JSFIDDLE LINK
Related
I know that is a bad practice to have more than HTML elements having same ID. However such is my situation where I need to specifically modify either of them.
I researched around and found about Jquery method 'document.getElementByID' that returns with the first similar element and lets you change it using css. Using that I wrote the code below but it doesn't work.
$(document.getElementById('it_trending-3')).css({"display":"none"});
I have added this code in my wordpress theme using the CSS-JS-PHP wordpress plugin, created a shortcut from the same and then added the shortcode. Can someone please guide me what and where I went wrong?
Also feel free to suggest a different function that would maybe let me specifically point to each of the same ID elements using maybe indexes. Thanks!
Keep a class to the divs you want to change:
<div>
<span id="a" class="test">1</span>
<span id="b" class="test">2</span>
<span>3</span>
</div>
The Jquery would go like this:
$(function() {
var w = $("div");
console.log($('#a').length);
console.log($('body #a').length);
console.log($('#a', w).length);
});
$(".test").first().css({"color":"orange"});
//or
$(".test:first").css({"color":"orange"});
But if you want to select any specific element with the class via an index of sorts, then you would need to do it like this:
var x = $(".test");
$(x[1]).css({"color":"orange"});
You can achieve this in 2 ways.
Based on element's hierarchy or based on class attribute / custom data attribute to the element.
In the below example we have 3 span elements with the same id and we have to apply 3 colors to each of those span elements.
HTML
<div>
<span id="it_trending-3">
Applying css to same Id with hierarchy (span in 1st div)
</span>
</div>
<div>
<span id="it_trending-3">
Applying css to same Id with hierarchy (span in 2nd div)
</span>
</div>
<br /><br /><br />
<span id="it_trending-3" class="testcls">
Applying css to same Id with class
</span>
Applying css using js / jquery based on element hierarchy
JQuery
(function($){
$("div:last #it_trending-3").css("color", "red");
$("div:first #it_trending-3").css("color", "green");
})(jQuery);
Based on class attribute / custom data attribute to the element.
JQuery
(function($){
$("#it_trending-3.testcls").css("color", "blue");
})(jQuery);
JS Fiddle Demo
I have the following HTML:
<span class="thumbnav" id="?"><?php get_the_image(); ?></span>
<span class="thumbnav" id="?"><?php get_the_image(); ?></span>
<div class="?" style="display:none;">
Some image, and a bit of text are staring at you.
</div>
<div class="?" style="display:none;">
Some image, and a bit of text are staring at you.
</div>
My goal is to use jQuery to find the ID value for every <span>, then use that ID to set a .click() event that will trigger a .show() function on the <div> elements.
So far I have this:
var clasid = $(".thumbnav").attr("id");
$("#" + clasid).click(function () {
$("." + clasid).show();
});
Which works, but only for the first <span>.
So I was wondering if there is a way to make this script work for all the spans, I read the jQuery documentation and they suggest using either .map() or .each(), but I haven't been able to figure it out.
Also it would be great if anyone could give me a hint on how to hide a <div> that was active when a new <div> is being displayed.
Thanks!
you can write class event and dynamically access that element id:
$(".thumbnav").click(function(){
$("." + this.id).show(); // this.id will give you clicked element id
})
See FIDDLE EXAMPLE
You can simply bind them using:
$(".thumbnav").click(function () {
$('.'+this.id).show();
});
Is there a JavaScript method similar to jQuery .next()? I want to find the next element that has the class of "error" relative to the element. I've tried using .nextSibling as a loop but couldn't figure it out. Didn't know if there was an easier way to go about it without jQuery.
For instance, if I have this code:
<div id="section">
<div id="test">test</div>
<span class="info">Information</span>
<span class="error">Error!</span>
</div>
I'm trying to get the next .error class closest to #test, if I have a #section2 and a #test2 I would want to get the .error class closest to #test2 and so on.
The nextElementSibling property returns the element immediately following the specified element, in the same tree level.
Example: Get the HTML content of the next sibling of a list item:
var x = document.getElementById("item1").nextElementSibling
The nextElementSibling property might help.
Best bet would be to search through the jQuery code and see what they did.
http://code.jquery.com/jquery-2.0.3.js
At a glance, I do see some calls to "nextSibling" and "previousSibling."
Also see here:
How to get next element using JavaScript-only?
Hope this helps!
This is the pure javascript for you:
HTML
<div id="nodes">
<div class="error">This is error Node</div>
<div class="nextElement">This is next Element</div>
</div>
Javscript:
var nodes = Array.prototype.slice.call( document.getElementById('nodes').children ),
errorNode = document.getElementsByClassName('error')[0];
var indexOfError = nodes.indexOf(errorNode);
var nextElement = nodes[indexOfError + 1];
alert(nextElement.innerText);
Here is demo
Sounds like you may be looking for document.getElementsByClassName()... if the elements with class=error are not direct siblings in the DOM, then there's not a good way to find them otherwise. It's elementary, but you can just search through the array returned by document.getElementsByClassName('error') until you find your starting element, and then you know the next item in the array will be the next element in the DOM.
See also MDN reference. Won't work in old IE, but works for all modern browsers.
I have several of these html blocks on a page in this structure
<div class="listing">
<h4>Some test Entry here</h4>
<div class="entry clearfix">
<a href="#" class="btn">
Text Here
</a>
</div>
</div>
I have the click event on the '.entry .btn' which is firing fine. But I want to get the inner text of the 'H4 a' within the same listing block as the btn I clicked. I have tried the following but just cannot seem to get the H4 text.
var getTitle = $(this).parents("h4").first();
alert(getTitle.html());
I have also tried closest() but still cannot get the H4? Any ideas?
closest & parents looks for ancestors. But, h4 is in another children of parent .listing.
Try:
var getTitle = $(this).closest('.listing').find("h4").first();
Firstly You need to traverse upwards in the DOM structure to identify the target element using .parent() or .parents() functions.
For your requirement you dont need the immediate parent hence .parent() is of no use instead you need to use .parents() to get all the ancestors in the DOM and refer the one with class selector .listing & finally traverse inward to find the target element h4.
JS CODE:
$('.btn').on('click',function(){
alert($(this).parents('.listing').find('h4').html());
});
Live Demo # JSFIDDLE
Happy Coding :)
use prev function in jquery
var getTitle = $(this).prev().find("h4").first();
alert(getTitle.html());
I am working with the google maps drawing manager. They don't put id's or class names on the drawing tools button bar so I'm trying to do this myself.
First I want to remove the circle button which the below works fine, but I want to add my own button so need to add a class name to the parent div "gmnoprint" but google has about 5 div's all with the same class name. I just want to add it to the one where the circle button was found.
<div class=gmnoprint"></div>
<div class=gmnoprint"></div>
<div class=gmnoprint"></div>
<div class=gmnoprint">
<div>
<div> <== This is what I found in my search
<span>
<div>
<img></img>
</div>
</span>
</div>
</div>
</div>
I am able to find the element I want and remove it, but adding a class to its wrapper div is proving a bit difficult for me.
This works for removing the button
$(".gmnoprint").each(function(){
$(this).find("[title='Draw a circle']").remove();
});
This doesn't work.. Just add's the class to all ".gmnoprint" div's
$(".gmnoprint").each(function(){
$(this).find("[title='Draw a circle']").remove().parent().addClass("test");
});
remove() removes the element from the DOM and returns the free-standing jquery object which has no connection to the DOM at all. A call to parent() after calling remove() is incorrect and that likely is the cause for your issue.
Try splitting your statements to:
var toRemove = $(this).find("[title='Draw a circle']");
toRemove.parent().addClass("test");
toRemove.remove();
You can use jQuery insertAfter and out your button after that default button then remove it.
$(".gmnoprint").each(function(){
var defBtn = $(this).find("[title='Draw a circle']");
$('<button class="my-button" />').insertAfter(defBtn);
defBtn.remove();
});
Or use jQuery after like this:
$(".gmnoprint").each(function(){
$(this)
.find("[title='Draw a circle']")
.after($('<button class="my-button" />'))
.remove();
});
You can use child selector to target the elements
$(".gmnoprint > div > div").addClass('myClassName');
At that point you could replace the html of the whole div , or find the span and replace it's inner html. Using html() method you don't need to use remove() as it will replace all contents of the element(s)
$(".gmnoprint > div > div").addClass('myClassName').find('span').html('<newButton>');
API Reference : http://api.jquery.com/child-selector/