How to use $(this) inside JS function and then find attr? - javascript

How do you use $(this) with a JS function and then find the attr?
function date_box() {
alert(this.getAttribute(week));
}
I want to get the attribute week from an element called gospel_table4. On click of gospel_table4, the function is triggered:
<a href='#'><div id='gospel_table4' week='$one_date' onclick='date_box()'> Week $one_date </div></a>
I can't do this:
$(this).click...
Because only one element of gospel_table4 is clickable. With the other method, all the elements of gospel_table4 are clickable.
Basicially, how do I get the attr from the function of date_box()?

You need a param inside your function
HTML:
<a href='#'><div id='gospel_table4' week='$one_date' onclick='date_box(this)'> Week $one_date </div></a>
Javascript:
function date_box(thisdiv){
alert($(thisdiv).attr("week"));
}

JAVASCRIPT
function date_box(that)
{
$attr=that.getAttribute('week');
alert($attr);
}
<a href='#'><div id='gospel_table4' week='$one_date' onclick='date_box(this)'> Week $one_date </div></a>

so the reason why click is not working is that div is inside anchor tag,
and anchor is clicked there are references like Anchor tag becomes non-working link in a div with float: right; or Is putting a div inside an anchor ever correct? which can give more details. So following is the code in jQuery()
$("#gospel_table4").parent("a").click(function(){
var week = $(this).children("#gospel_table4").attr("week");
console.log(week);
});
Explanation : Since we know that anchor is clicked first we place the click event listener on anchor tag . Then we can access the relative child element.
This will work but date_box() will also be invoked at the same time, I would recommend that you remove the onclick and and place it in side the above that way you would have more control over the code. Hope this is helpful.

Related

How can I get text from href?

I've got problem with getting this text from href. I'm working on dom and I'd like to get text from this href:
<div class='xx'>
<a href='zz' class='button>
...
I was trying to do sth like that:
document.getElementById(".xx").getAttribute("href")
But it's not working properly
But it's not working properly
Because
you don't have an element with id attribute .xx,
.xx targets the div not the anchor
Also, your anchor tag's attribute class is not closed properly, also closing tag is not given either.
<div class='xx'>
<a href='zz' class='button'>Some text</a>
</div>
you have a class so use the class selector itself using querySelector
document.querySelector( ".xx .button" ).getAttribute( "href" )
or simply
document.querySelector( ".xx .button" ).href;
getElementById will grab an element by that ID. You have an anchor (malformed albeit) with not an ID but a class. Secondly you are targeting the parent div. You should be targeting the tag using querySelector() instead. Then to get the href you'd use href.
const href = document.querySelector('.xx .button').href;
console.log(href);
<div class='xx'>
<a href='zz' class='button'></a>
</div>
This works for me
document.getElementsByClassName("xx")[0].getElementsByTagName("a")[0].getAttribute("href")
The code below will get text from link:
var x = document.getElementsByClassName('xx')[0].getElementsByTagName("a")[0].getAttribute("href");
you can use id instead of class because class returns undefined value.and also you tried to get class using getby id
wrong:
document.getElementById(".xx").getAttribute("href")
function h()
{
alert(document.getElementById("button").href);
}
<a href='zz' id='button' onclick='h();'>
asd</a>
var yourhref = document.querySelector("div.xx a.button").href
yourhref holds your requested value. This is as precise as it gets using only the part of code you provided. If somewhere else on the page you have a div with class xx and a link with class button you are not gonna have a good time.
Solution - either have your targeted element or parent have UNIQUE id and then write a selection from there.

how to show the div using this in jquery

what i need
i just need to show div.
code
<a href="javascript:void(0);" id="viewdetail" onclick="$(this).show();" style="color:green">view detail
<div class="speakers dis-non">
</div>
</a>
when I changed code to onclick="$('.speakers').show();" then its working fine.
problem occurs:
onclick="$(this).show()"
no div is shown.
i need when user click on particular anchor element then data should of that particular link click should be shown.
You have to target element using:
$(this).find('div').show();
Or to make it more specific with:
$(this).find('.speakers').show();
$(this) refers to the element you click on, in this case the a tag and not the div you want to show.
Try $(this).children('div').show();
This will show the div inside the anchor tag
$(this).children(".speakers").show();
You have to select first div element using:
$('this').children('div').show();
$(this) refers to the clicked anchor instead of the div. Use $(this).children('div.speakers').show(); to target div with speakers class inside the anchor.
<a href="javascript:void(0);" id="viewdetail"
onclick="$(this).children('div.speakers').show();"
style="color:green">view detail
<div class="speakers dis-non">
</div>
</a>
Working demo: http://jsfiddle.net/fw3sgc21/

get id of anchor inside list item, Javascript

Using Javascript, How to get id of list item, onclick of anchor tag inside list item. Ex.
<ul id="ul1">
`<li id=li1">Click</li>`
</ul>
Thanks to everyone
$('li').on('click', function(){
var $this = $(this), id = $this.attr('id');
// do something with id
});
This works because you the this variable refers to whatever li was clicked on
If you want the id of the parent:
$('a').on('click',function () {
var id = $(this).parent().attr("id");
// some script
});
EDIT
Take into considerations NewbornCodeMonkey's comment about the href linking to a different page...
Plain Javascript
You will need to add an onclick event to your anchor. You can't do it unobtrusively. So:
<a onclick="myfunction()" href="...">...</a>
javascript:
function myfunction() {
var id = this.parentNode.id;
// some script
}
The issue with your current code is that you will be redirecting your page from the anchor tag. You can use the href attribute to instead call a javascript function, or remove the anchor tag and use jquery to react to a mouse event using either the click function or the on function with click as a parameter.
Using the anchor tag, you can do something like this:
<li id=li1">Click</li>
function myClickFunction(){
var id = this.parentNode.id;
// use ID here
};
NOTE: If you still wish to redirect, then you can also leave the anchor tag pointing to page1.html, and use jquery to listen with one of the above functions that I have linked (.on or .click)
Another option instead of jquery is the getAttribute function
an example of getAttribute:
document.getElementsByTagName("a")[0].getAttribute("id");

When a Div class is clicked, alert it's inner content's Div Class

How do i even put these, let me try. In the following sets of codes, i want to click 'parentclass' and have an alert value of 'child1' and when i click the class below it which is 'Parent 2' have an alert fire with a value of 'child2'
So this must alert the content of that class only and not the entire class.
Here's some Javascript in Jquery.
var childclass = $('.childclass').html();
$('.parentclass').click(function(e) {
alert (childclass)
});
$('.childclass').click(function(e) {
e.stopPropagation()
e.preventDefault()
});
And HTML
<a href="" onClick="return false">
<div class='parentclass'>
Parent 1
<div style="display:none" class="childclass">child1</div>
</div>
</a>
<a href="" onClick="return false">
<div class='parentclass'>
Parent 2
<div style="display:none" class="childclass">child2</div>
</div>
</a>
This line var childclass = $('.childclass').html(); doesnt make sense as it doesn't know which element in particular you mean. The result of that will just be child1child2 which is just a concatenation of the .html() of all the elements with class childclass. This is obviously not what you want.
Therefore you should dynamically find the child with a class of childclass upon receiving the click event.
$('.parentclass').click(function(e) {
alert($(this).find('.childclass').html())
});
Also, you should know that your child class event handler is useless as we don't care if the event gets propogated downwards. If you DID care, then your e.stopPropagation() and e.preventDefault() should be in the event handler of the parent class.
You need to fetch the html of the clicked parent element within the click handler
$('.parentclass').click(function (e) {
alert($(this).find('.childclass').html())
});
$('.childclass').click(function (e) {
e.stopPropagation()
e.preventDefault()
});
Demo: Fiddle
Several ways you can go about this.
First, if your HTML will not be dynamic (elements already exist when page loads), then you can select elements by the parent class name and assign click event as so:
$('.parentclass').click(function(e) {
// the first variable here is selecting the inner elements having class 'childclass'
// keep in mind, if more than one child having that class is present within this parent, it will select all of them
var child = $(this).find('.childclass');
// here we alert the text of the inner child found
// if it is more than one, you will have undesired results. you may want to specify `.first()`
alert(child.text())
})
For newer jQuery you can also use $('.parentclass').on('click', function(e) {.
If you expect any pieces of parentclass to be dynamic, then you'll want to delegate the event based on either a static parent to the parents or document. This can be like so:
$(document).on('click', '.parentclass', function(e) {
alert($(this).find('.childclass').text())
})
Or, if you have a static (already there when page loads) wrapping element, give it an ID like `parentClassWrapper' and assign the click event dynamically as:
$('#parentClassWrapper').on('click', '.parentclass', function(e) {
alert($(this).find('.childclass').text())
})
Some helpful links:
jQuery API
jQuery Selectors
.click()
.on()
Some info on Event Delegation
jquery on vs click methods
jQuery .on('click') vs. .click() and .delegate('click')
jquery .live('click') vs .click()
I made several adjustments to your html that are worth noting. There's no need for the <a> tag. Don't use inline js - onlick in your html. Note that I wrapped the text inside of the div in the <a> tag instead. This markup is more semantic. Also, move your styles to css rather than in the html.
<div class="parent">
<a>Parent 1</a>
<a class="child">child of parent 1 contents</a>
</div>
<div class="parent">
<a>Parent 2</a>
<a class="child">child of parent 2 contents</a>
</div>
css:
.parent > .child { /* good practice: only select an immediate child of the parent */
display: none;
}
The other answers here are using find() to select the child, but I recommend children() instead. For example, if you had additional nested .childs, find() will select them all, but children() will only select direct .childs of the parent, so it is better in this case. I also recommend using the console for debugging rather than alert.
Live demo here (click).
$('.parent').click(function() {
var $child = $(this).children('.child');
var cls = $child.attr('class');
console.log(cls);
$child.show(); //added so that you can click the child
});
$('.child').click(function() {
var html = $(this).html();
console.log(html);
//if you just want the text, use this instead:
var text = $(this).text();
console.log(text);
});

this.appendChild is not a function

I have JS below that i am trying to dispaly a menu item once the image is clicked under the image and once an item is clicked it disappears. i have multiple images that is why i am building this dynamic content menu. i am planning to add bunch of html element inside userMenuContent by
using var userMenuContent ="<div><form>...</<form></div>";
but to begin with my small test fails
function userMenu() {
var userMenudiv = document.createElement("div");
userMenudiv.setAttribute("class", "statusContainer");
var userMenuContent = "<p>test</p>";
$(userMenudiv).append($(userMenuContent));
$(userMenudiv).hide();
this.appendChild(userMenudiv);
$(userMenudiv).slideDown();
}
<img class="icon" src="image.png" onclick="userMenu()"/>
when i click the image i get
TypeError: this.appendChild is not a function.
i am using jquery 1.8.3 and jquery-ui1.8.24
'this' refers to the window object, not the image.
Don't use inline event handlers. Give the DOM element an id and select it that way.
You can't add a div to an image. Instead, you need to specify another target element
Since you're using jQuery, just do it the jQuery way.
$(document).ready(function(){
$('#userMenuImg').click(function(){
$('#target')
.append('<div class="statusContainer"><p>test</p></div>')
.slideDown();
});
});
<img id="userMenuImg" class="icon" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRMKbTxKTOJbJvVTt2SZak49lARNnCU4D7ECfZn1KspIn6SXDHz3A">
<div id="target"></div>
​
​

Categories