Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to select a specific parent of every element that has a title attribute that starts with "Mod" and put them in a single var that I can then easily control.
var allMods= $('#main-element .object[title^="Mod"]').closest('.specific-parent');
$(allMods).hide();
but it only works on the first found element, I can't understand how to set the var to be every match, can someone give me a hand please?
It should work provided all of the .object[title^="Mod"] elements are within the #main-element container.
Example: Live Copy | Source
HTML:
<div id="main-element">
<div class="specific-parent">
<div class="object" title="Mod1">Mod1 - turns green</div>
</div>
<div class="specific-parent">
<div class="object" title="Mod2">Mod2 - turns green</div>
</div>
<div class="specific-parent">
<div class="object" title="Mod3">Mod3 - turns green</div>
</div>
</div>
<div>
<div class="specific-parent">
<div class="object" title="Mod4">Mod4 - does <strong>not</strong> turn green</div>
</div>
</div>
JavaScript:
$('#main-element .object[title^="Mod"]').closest(".specific-parent").css("color", "green");
Result: Only the .specific-parents of .object[title^="Mod"] elements that are within #main-element turn green.
As per the Docs:
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
You probably want .parents() (note the S, .parent() also returns only ONE element)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I've got a very amateur question since I am very new to coding!
I have 4 button inputs "skolefag", ""sport", "fritid", "diverse" and 4 large squares (stacked upon eachother, different colors, but you can only see the red one)
I want to switch between divs (the large squares) when i click on the different categories, so that the contents and background color of the correct/matching large square shows.
What would be the easiest technique to achieve this trough?
Sorry again and thank you in advance!
You need to use onclick attribute on you button or add a click eventListenner to it.
Then you create a function that is called by onclick="myfunction(idButton)" or by your eventListener :
function myfunction(idButton) {
document.getElementById("my-elmt-to-set-up").backgroundColor = docuement.getElementById(idbutton).backgroundColor
}
and same thing for color properties, review javascript lesson I think --> after lesson you can make some incredible interactions
Here is one solution (which I think is neat):
document.addEventListener("DOMContentLoaded", function() {
change_menu("home");
});
function change_menu(
menu_to_show
) {
['home', 'second', 'third'].forEach(function(memuee) {
document.getElementById(memuee).style.display = 'none';
});
document.getElementById(menu_to_show).style.display = 'block';
}
<div style='display: flex;font-size: 200%;'>
<div>
<div style="background:green" onclick="change_menu('home')">Home</div>
<div style="background:red" onclick="change_menu('second')">Go To Second</div>
<div style="background:blue" onclick="change_menu('third')">Go To Third</div>
</div>
<div id="home" style="background:green">
HOME PAGE
</div>
<div id="second" style="background:red">
SECOND PAGE
</div>
<div id="third" style="background:blue">
THIRD PAGE
</div>
</div>
Of course this could be further optimized by referencing "page" divs by the "button" div's ids (e.g. home_page from home_button) or grouping ids within given "wrapper" divs, using classes, etc., but I think this is the essential solution.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm playing with the following incoming HTML structure that I don't control:
<div id="someRandom1">
<div id="someRandom2">
<div id="someRandom3">
<div id="someRandom4">
...
<p>Actual content</p>
<ul>
<li>This is a thing I need too</li>
</ul>
And this
<p>Some more content</p>
...
</div>
</div>
</div>
<p id="additionalGarbage">Don't need this</p>
</div>
What I'm trying to accomplish is to end up with the following:
<p>Actual content</p>
<ul>
<li>This is a thing I need too</li>
</ul>
And this
<p>Some more content</p>
I don't know how many divs there will be but I do know there's only one child div and the stuff inside the last div is what I need. Logic should probably be to check for a child div, get the contents and check for a child div. If another child div, do check again or else finally return the content. Every loop I've written so far crashes Chrome so I'm obviously writing it wrong. Please advise.
EDIT: After all the comments, I'll try to make this more concise in some bullets.
There's an unknown number of nested divs. (I don't have any control of this).
The child div may or may not be the first element inside the parent div.
The html structure in the deepest div needs to be kept in tact.
Bonus: minimal lines of code.
Assuming...
you have the top level (since you said you're getting it from an API)
you only need to remove the outermost divs (by tag name)
the divs targeted for removal will be the first div among its siblings (though there may be other elements with different names around it)
...you can do this:
// Assumes you have a handle on the root level
var node = $("#someRandom1");
var div = node.children("div")
while (div.length) {
node = div.first()
div = node.children("div")
}
// now node.children will be the content
alert(node.children().map(function(i, n) { return n.nodeName }).toArray())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="someRandom1">
<p class="garbage"></p>
<div id="someRandom2">
<p class="garbage"></p>
<div id="someRandom3">
<p class="garbage"></p>
<div id="someRandom4">
...
<p>Actual content</p>
<ul></ul>
<p></p>
...
</div>
</div>
<p class="garbage"></p>
</div>
<p id="additionalGarbage"></p>
</div>
This simply starts with the outermost div, and if it has at least one div div, it traverses down to that. So you end up with node being the innermost consecutive div child and node.children holds its content nodes.
This shall do the trick:
document.getElementById( 'someRandom1' ).querySelector( ':not(div)' ).parentNode.innerHTML
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
A have e3 and e2 divs, and parent div e.
There is too many e divs on the page.
How can I get e3 div value when I click on div e2?
Thanks.
There is no value attribute for div. You could get the innerHTML through javascript.
var divValue = document.getElementById('e3').innerHTML;
Let me first tell you how i understood the question. This is kind of how your html is structured:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="e">
<div id="e2">
i am e2 text
</div>
<div id="e3">
i am e3 text
</div>
</div>
<div id="e">
another e text
</div>
And this is the js code that will give the content of the e3 div when the user click on the e2 div.
$(document).ready(function(){
$("#e2").click(function(){
alert($("#e3").html());
})
});
Hope this helps :)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to get the closest/nearest class of a specific element.
How can I make it work? I am currently trying to use .closest.
HTML
<div class="test">.test</div> <!-- Not this -->
<div>
<div class="test">.test</div> <!-- That's the one I need to grab -->
</div>
<div id="test"></div> <!-- This is the reference element -->
<div class="another"></div>
<div class="another"></div>
<div class="test">.test</div>
JS
var test = $('#test2').closest('.test');
console.log(test);
If closest isn't the right method, how can I actually grab the closest 'test' class?
I tried parentsUntil() as well.
Actually if that can help, in my use case I will ALWAYS need the nearest PARENT element of a specific class, whether that parent element is within another element or not, like in this HTML example.
If I understand correctly then you are looking for the nearest element that appears before a specific element in HTML source order (and you do not know/cannot change the HTML structure). The simplest solution is this:
jQuery() collections are sorted in the order in which the elements appear in DOM (unless the documentation states otherwise). So we have:
$("#test, .test")
// [div.test, div.test, div#test, div.test]
// ^ ^
// | +---- reference element
// +-------------- nearest element before it
//
// notice that the elements are sorted in the order they appear in HTML
Just combine this with jQuery.index():
$(function() {
var $ref = $("#test");
var $col = $(".test").add($ref);
var index = $col.index($ref);
$col.eq(index - 1).css("background-color", "orange");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="test">.test</div> <!-- Not this -->
<div>
<div class="test">.test</div> <!-- That's the one I need to grab -->
</div>
<div id="test"></div> <!-- This is the reference element -->
<div class="another"></div>
<div class="another"></div>
<div class="test">.test</div>
Not sure, why your HTML is structured like that, but this should select your required div:
$('.test',$('#test2').prev('div')).text() // find a div with class test, contained within div that lies previous to #test2
Closest searches for parent elements in DOM tree. For siblings you cannot easily get the nearest as such, but if you know direction up/down you can select from .nextAll('.test:first') and prevAll('.test:first').
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a chat support fixed on the left of my browser, I want to show and hide it using jQuery, I already did it by using the show() and hide() function but, when I want to apply the same jQuery effect on subsequent layers it does nothing, it just applies to the first element, what I want to ask is:
What is the best way to do this, I'm learning jQuery and have done some little things with this library but I can't figure how to do this without just copy and paste the same effect, should I use a "for" method?.
I leave my code below with a JS Fiddle example so you guys can figure out what's going on:
HTML Markup:
<div id="support_left">
<div id="support_show">
<figure id="show_control">
<img src="../img/chat.png" alt="Chat" />
</figure>
<div id="show_item">
<p class="support_cyan">Chat with sales <span class="close">X</span></p>
</div>
</div>
<div id="support_show">
<figure id="show_control">
<img src="../img/call.png" alt="Call" />
</figure>
<div id="show_item">
<p class="support_orange">Chat with sales <span class="close">X</span></p>
</div>
</div>
<div id="support_show">
<figure id="show_control">
<img src="../img/mail.png" alt="Email" />
</figure>
<div id="show_item">
<p class="support_green">Chat with sales <span class="close">X</span></p>
</div>
</div>
</div>
Javascript:
$('#show_item').hide();
$('#show_control').click(function(){
$('#show_item').show();
});
$('.close').click(function(){
$('#show_item').hide();
});
Link to the JS Fiddle:
http://jsfiddle.net/45hsd6dp/
Thanks in advance.
First of all, change all your IDs to classes. IDs must be unique and how jQuery handles multiple instances of IDs is up to how individual browser/vendor decides to do with it. The behaviour is technically undefined and the browser will only select the first occurence, usually.
You will need to give your show and hide functions a context when the click event is fired. With your current script, you are telling jQuery that:
Whenever a click event is registered for any elements with the class .show_control, show ALL items that has the class .show_item.
See that there is no context in your function that is bound to the click event.
To give your event listening a context, always use $(this), which restricts the function to elements of interest:
$('.show_item').hide();
$('.show_control').click(function(){
$(this).next('.show_item').show();
});
$('.close').click(function(){
$(this).parent('.show_item').hide();
});
In layman's words, the function tells jQuery:
When .show_control is clicked it, search for it's immediate, next sibling that has the class of .show_item, and show it.
See that the statement has context, because $(this) restricts jQuery to the context of the element being clicked on. Depending on your markup, you will have to rely on various jQuery methods to transverse the DOM, such as .next(), .prev(), .parent(), .parents(), .find(), .children(), .siblings() and etc. All these functions are well-documented on the jQuery API, make sure you check that out.
See fiddle here: http://jsfiddle.net/teddyrised/45hsd6dp/6/