How can i get the Id from the next element? - javascript

I'm trying to get the ID from the next element, but i get this - "undefined"...
What am i doing wrong?
http://jsfiddle.net/84x9v/
HTML:
<a class="col" onclick="getId()">
<div id="1"><span>1</span></div>
</a>
JavaScript:
function getId(){
var get = $(this).next("div").attr("id");
alert(get);
}

remove the inline js
<a class="col">
<div id="1"><span>1</span></div>
</a>
and use an event handler
$('.col').on('click', function() {
var get = $(this).find("div").prop("id");
alert(get);
});
note that putting a block element inside an anchor generally isn't very good practice, and the div is a child of the anchor, it's not the next sibling.

'cause it's not the 'next' element.
function getId(){
var get=$(this).find("div").attr("id");
alert(get);
)
should work...

You're using jQuery and .next() wrong. Remove the inline event handler, use .find() instead of .next(), and try:
function getId() {
var get = $(this).find("div").attr("id");
alert(get);
}
$('a').click(getId)
jsFiddle example

Related

In JavaScript and HTML, how can I get the access to the <div> that the current button locates?

In HTML, I have
<div>
<button onclick="action()">button</button>
</div>
Without giving an ID or class to the div element, what can I do in JavaScript to get an access to it and use it?
Pass this into action:
<button onclick="action(this)">button</button>
and then in action
function action(btn) {
var div = btn.parentNode;
// ...
}
or if you want a bit more flexibility, use the (relatively-new) closest method:
function action(btn) {
var div = btn.closest("div");
// ...
}
Side note: Rather than onxyz-attribute-style event handlers, consider using modern event handling (addEventListener, attachEvent on obsolete browsers). If you have to support obsolete browsers, my answer here provides a function you can use to deal with the lack of addEventListener.
Grab the event then get the currentTarget then find the parentNode. Very simple way to do it. This will work no matter which element is clicked. Please see code snippet demonstration.
function getParentNode(event) {
console.log(event.currentTarget.parentNode);
}
<div id="div1"><button onclick="getParentNode(event)">Click</button></div>
<div id="div2"><button onclick="getParentNode(event)">Click</button></div>
using this in the onclick=action() and then the parent is .parentNode
then your method would look like :
<div>
<button onclick="action(this);">button</button>
</div>
function action(el) {
console.log(el.parentNode);
}
but I rather prefer .addEventListenerand for your next question then :
var $el = document.getElementById("a");
$el.addEventListener("click", function(e) {
// Create a <button> element
var btn = document.createElement("BUTTON");
// Create a text node
var t = document.createTextNode("CLICK ME");
// Append the text to <button>
btn.appendChild(t);
// Append <button> to the parentNode
this.parentNode.appendChild(btn);
});
<div>
<button id="a">Button</button>
</div>
Also in case you wonder for a shorter version and probably introducing to the jQuery :
;$(function(){
$("#a").on("click", function(e) {
$(this).parent().append('<button>Click Me</button>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id="a">Button</button>
</div>
Another but not straight way to get the parent instead of .parentNode is .closest() method:
element.closest("div"); // also supported in jQuery
Returns the first ancestor of element, that is a <div> element:
If it is possible, pass this (button) to action. Then you can access parent by element.parentNode. Example: https://jsbin.com/fidufa/edit

creating a link to images

I am trying to create a jquery code which can wrap an img tag with a link:
My code is like this:
http://prntscr.com/iuw6hc
I will paste my HTML here but basically it is a loop of many items showing within each col.
<div class="car-item gray-bg text-center first" style="height: 357px;">
<div class="car-image">
<img class="img-responsive" src="http:///wp-content/uploads/2018/03/20180214_090633-265x190.jpg" alt="" width="265" height="190">
<div class="car-overlay-banner">
<ul>
<li><i class="fa fa-link"></i></li>
I am trying like this:
var wrapped = false;
var original = $(".img-responsive");
$(".img-responsive").click(function(){
if (!wrapped) {
wrapped = true;
var gURL = $('.car-overlay-banner').find('a').attr('href');
$(".img-responsive").wrap("");
}
});
$(".img-responsive").click(function(){
if (wrapped) {
wrapped = false;
$(".img-responsive").parent().replaceWith(original);
}
});
Trying to use a href of car overlay to apply to the image too.
jQuery provides a method named "wrap()", which can be used to insert any HTML structure in set of matched elements. In simple words, if you want put wrapper around your div element then you can use wrap() method. For example, you have a div with ID "Child".
<div id="Child"></div>
And want to wrap this div with any parent then you can use "wrap()" method to insert HTML.
$('#Child').wrap('<div id="Parent"></div>');
<div id="parent">
<div id="child"></div>
</div>
Same way, we will use the wrap() method to insert hyperlink to image tag so that the image becomes clickable. See below.
$(document).ready(function() {
$("#imgLogo").wrap('');
});
In this example, I have used ID as selector but you can use class selector to find all the images with same class and then wrap them with tag. You can also assign target="_blank" in the above tag to open the link in new window.
I think you need code like this?
var wrapped = false;
var original = $(".img-responsive");
$(".img-responsive").click(function(){
if (!wrapped) {
var wrapped = true;
// find link href in .car-image(img-responsive's parent)
var gURL = $(this).parent().find('a').attr('href');
// use $(this) instead of $(".classname") to apply link only clicked image
$(this).wrap("");
}
});
$(".img-responsive").click(function(){
if (wrapped) {
var wrapped = false;
$(this).parent().replaceWith(original);
}
});

Access elements inside a div outside of the current div

This is probably a very easy approach, however I haven't been able to figure it out.
My approach is to get all <img> elements that have the "expanded-image" class that are within the "img-preview" of my current "entry".
This is my html:
<div class="entry">
<div class="img-preview">
<img>
<img class="expanded-image" style="display:none;">
</div>
<div class="content">
[..]
[..]
<span class="more-text"></span>
[..]
[..]
</div>
</div>
And this is the JS I work with:
$('.content').each(function(event) {
$(this).find('span.more-text').click(function(event) {
// TODO
});
});
Firstly you don't need the each() at all as you can apply the click() event handler to all elements within a single selector.
To solve your issue you can use closest() to find the nearest parent .entry element to the clicked .more-text. From there you can find() all the .expanded-image elements. Try this:
$('.content span.more-text').click(function(event) {
var $imgs = $(this).closest('.entry').find('.img-preview .expanded-image');
// work with $imgs here...
});
$('.content').each(function(event) {
var $content = $(this);
$(this).find('span.more-text').click(function(event) {
$content.parent().find('.expanded-image'); // there you go
});
});
Use o combination of closest, prev and find
$('span.more-text').click(function(event) {
$(this).closest('.content').prev().find('.expanded-image');
});
You can use closest() to bubble up to find the parent given in the selector. Then from there you can navigate down to the required elements.
$(this).closest('.entry').find('.img-preview .expanded-image');
Also as Ron has suggested you dont have to loop and then bind the click events. You can simply do
$('.entry .content .more-text').click(function(){
$(this).closest('.entry').find('.img-preview .expanded-image');
})

How to get sibling element (div) in Javascript?

So I have this HTML:
<div class="tip-box">
<div class="tip-title" onclick="toggleTip()">
<h2>Tip 1</h2>
</div>
<div class="tip-content hidden">
<p>Tip 1 content</p>
</div>
</div>
And this Javascript:
function toggleTip() {
$(this).siblings(".tip-content").toggleClass("hidden");
}
Hopefully it's obvious what this is supposed to do, but it doesn't work. Using .siblings() just doesn't seem to work in this way.
What's the correct solution for this? To get the next sibling of a certain type or with a certain class and then hide/show it?
You can use Jquery function.
<div class="tip-box">
<div class="tip-title">
<h2>Tip 1</h2>
</div>
<div class="tip-content hidden">
<p>Tip 1 content</p>
</div>
</div>
$(document).ready(function(){
$('.tip-title').click(function(){
$(this).siblings(".tip-content").toggleClass("hidden");
});
});
you can also use this
<div class="tip-box">
<div class="tip-title" onclick="toggloTip(this)">
<h2>Tip 1</h2>
</div>
<div class="tip-content hidden">
<p>Tip 1 content</p>
</div>
</div>
<script>
function toggloTip(elm) {
$(elm).siblings(".tip-content").toggleClass("hidden");
}
</script>
You can use pure javaScript with nextElementSibling property of node something like below,
I suppose you want do this operation with siblings.
function getChildrens(n, selector) {
var nodes = [];
while (n.nextElementSibling != null) {
if (n.nextElementSibling.hasOwnProperty('classList')) {
if (n.nextElementSibling.classList.contains(selector)) {
//return n.nextElementSibling;
nodes.push(n.nextElementSibling);
}
}
n = n.nextElementSibling;
}
return nodes;
};
function getSiblings(n, selector) {
return getChildrens(n, selector);
}
function toggleTip(elem) {
var siblings = getSiblings(elem, "tip-content");
if (siblings.length > 0) {
for (var i = 0; i < siblings.length; i++) {
siblings[i].classList.toggle("hidden");
}
}
}
.hidden {
display: none;
}
<div class="tip-box">
<div class="tip-title" onclick="toggleTip(this)">
<h2>Tip 1</h2>
</div>
<div class="tip-content hidden">
<p>Tip 1 content</p>
</div>
</div>
Here is another non JQuery answer.
To get the next element sibling use:
var nextElement = element.nextElementSibling;
To get the previous element sibling use:
var previousElement = element.previousElementSibling;
To get the element index use:
var index = Array.prototype.slice.call(element.parentElement.children).indexOf(element);
If you are at the first element the previousElementSibling value will be null.
If you are at the last element the nextElementSibling value will be null.
How about this JavaScript:
$(function(){
$('.tip-box').on('click', '.tip-title', function(){
$(this).next('.tip-content').toggleClass('hidden');
});
});
Remove the idea of working with onclick attributes when you use jQuery.
None of the previous answers, not even that serial-upvoted one ;), actually explains the problem and why their solutions work.
The problem is that an inline onclick handler does not pass on its current context. Inside the onclick="" JavaScript code this is the element clicked. Once you call a global function (like your toggleTip), that context is lost. The this the function receives is window and not the element.
The usual quick fix, for raw JavaScript code, is to pass this as a parameter to the global function.
e.g.
onclick="toggleTip(this)"
and receive a parameter in the function like this:
function toggleTip(element) {
$(element).siblings(".tip-content").toggleClass("hidden");
}
However, as you are using jQuery, inline event handlers are actually a bad idea. They separate the event registration from the event handler code for no reason and do not allow for multiple event handlers, of the same type, on the same element. They also bypass the rather cool event bubbling system jQuery uses.
The preferred alternative, with jQuery, is to use jQuery to select the element and jQuery to connect the event in one step:
jQuery(function($){
$('.tip-title').click(function(){
$(this).siblings(".tip-content").toggleClass("hidden");
});
});
As you only want the element that follows, and potentially will add more pairs, the better option would be using nextAll and first(), with the same jQuery filter, instead of siblings:
e.g.
jQuery(function($){
$('.tip-title').click(function(){
$(this).nextAll(".tip-content").first().toggleClass("hidden");
});
});
Or, of you can guarantee it is the next element, use next as #Tim Vermaelen did (with or without the selector makes no difference, so might as well leave it out):
jQuery(function($){
$('.tip-title').click(function(){
$(this).next().toggleClass("hidden");
});
});
Note: In this example jQuery(function($){ is a DOM ready event handler which is the rather handy shortcut version of $(document).ready(function(){YOUR CODE});, which also passes a locally scoped $ value. For those that mistake this code for an incorrect IIFE, here is a working example: http://jsfiddle.net/TrueBlueAussie/az4r27uz/

jQuery select the function selector

I'm trying to achieve something inside a function, to actually access the parent selector.
Here is a small snippet of my HTML code:
<div class="module-row module-tab pull-right" id="modtab-sql_net">
<img src="images/icons/icon-orangebox-plus.png" class="modtab-toggle">
</div>
<div id="tab-module-row-1">
</div>
<div class="module-row module-tab pull-right" id="modtab-sql_dss">
<img src="images/icons/icon-orangebox-plus.png" class="modtab-toggle">
</div>
<div id="tab-module-row-2">
</div>
Here is the jQuery script I tried:
$('div[id^="modtab-"]').click(function(){
$(this).next('div[id^="tab-module-row"]').toggle(function(){
$(this).next('.modtab-toggle').toggle_switch.attr("src").replace("plus", "minus");
// The above line is incorrect. I need to change img attr for the class which is inside the div being clicked
});
});
Now, I want to actually change the image icon from a "plus" to a "minus" (the filenames are kept such).
I need to change $(this).next('.modtab-toggle') in the code to something that can work.
Please do NOT suggest to simply access the class using $('.modtab-toggle') as I have multiple such div tags in the code. It won't work out that way.
Thanks for any help.
Try this:
$('div[id^="modtab-"]').click(function(){
$(this).find('.modtab-toggle').attr("src", function(i, attr){
var o = this.src.indexOf('plus') > -1 ? this.src.replace('plus', 'minus') : this.src.replace('minus', 'plus');
return o;
});
});
See the Demo # Fiddle
try something like this
$('div[id^="modtab-"]').click(function(){
var $this = $(this);// clicked div
$this.next('.tab-module-row').toggle(function(){
$this.find('.modtab-toggle').toggle_switch.attr("src").replace("plus", "minus");
});
});
Note: you should use class instead of id because it should be unique
#tab-module-row ->.tab-module-row
EDITED ANSWER
$('div[id^="modtab-"]').click(function(){
var $this = $(this);// clicked div
$this.next('div[id^="tab-module-row"]').toggle(function(){
var img = $this.find('.modtab-toggle'); // your image object
// your condition to check which image to display will goes here.
});
});
change $(this).next('.modtab-toggle') to $(this).find('.modtab-toggle') to make it work.
See find() docs here

Categories