Why this JS id does not work for multiple items - javascript

I got a 2 buttons and an image. When ever I press any of the buttons the image fades out. like this demo: http://jsfiddle.net/5wBuV/6/
the problem is that this is working only for the first button and the second one does not work. It might be a simple mistake but I am really beginning in JS.
$("#clickedButton").click( function() {
$("#hide").fadeOut("slow");
});

id of an element must be unique, if you use ID selector jQuery will return only the first element with the id.
In your case if you want to add same event handler to a set of elements, you can use a common class attribute and then use class-selector
<!-- The button -->
<a href="#" class = 'clickedButton'>
<img src="http://www.kwvs.pepperdine.edu/playbutton.png" />
</a>
<a href="#" class = 'clickedButton'>
<img src="http://www.kwvs.pepperdine.edu/playbutton.png" />
</a>
then
$(".clickedButton").click( function() {
$("#hide").fadeOut("slow");
});
Demo: Fiddle

Using id selector will only return zero/ one object.
If you want to refer to more than one object, use class selector. Like:
$('.clickedButton').click(function () {
$('#hide').fadeOut('slow');
});

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.

Can I use jquery to operate the name attribute of <a> tag?

In my web I have more than 5 links,some of them are in the same group. I want to make them hide or show together.So I give the same name to the common link.But How to operate them?
<a href='a.jsp' name='group1'>aa</a>
<a href='b.jsp' name='group2' >bb</a>
<a href='c.jsp' name='group1'>cc</a>
<a href='d.jsp' name='group2'>dd</a>
<a href='e.jsp' name='group1'>ee</a>
If use input,I can write like $("input[name='group1']").hide();.But now is link tag.How to operate them?
Classes are our friend - forget trying to use a name attribute - this is not the correct use for that. What you want to do is add a class and then alter the display based on the class:
//HTML
<a href='a.jsp' class='group1'>aa</a>
<a href='b.jsp' class='group2' >bb</a>
<a href='c.jsp' class='group1'>cc</a>
<a href='d.jsp' class='group2'>dd</a>
<a href='e.jsp' class='group1'>ee</a>
//js
$('.group1').hide();
you can also add css in the jquery
//js
$('.group1').css('display','none');
but the better way of altering the display state is to have a class that you then add or remove to the elements - that way you are not altering the actual css of the element:
//css
.hidden {display:none}
.shown{display:block}
//js
$('.group1').addClass('hidden');
you can also toggle the class - which allows you to show the elements simply by not hiding them
//js
$('.group1').toggleClass('hidden');
You can select all of the anchor tags with this the same code as you would use for input, but you just specify that you want to select the <a> tags, and then you can call the method hide().
$("a[name='group1']").hide()
The [name='name'] part of the code is called CSS attribute selector, and it can be used with most HTML tags.
See this:
https://css-tricks.com/almanac/selectors/a/attribute/
And this:
https://developer.mozilla.org/cs/docs/Web/CSS/Attribute_selectors
Although when doing something like this, it would be much better to use classes.

Clicking a different button inside each loop iteration

I'm having troubles with clicking an item inside an each loop (in CasperJS) here's a small part of the code:
$("#id1",html).each(function( index ) {/*loop-start*/
var job = {};/*init*/
casperjs.click(".class2");
boo.waitForSelector('selector3', function() {
job.url = casperjs.getCurrentUrl();
page.pagejobs.push(job);
casperjs.back();
casperjs.waitForSelector('selector4', function() {
},function(){
}, 6000);
},function(){
}, 10000);
});/*loop-end*/
Basically I'm clicking a button (casper.click(".class2")) that's fine no problem here. The first time it works fine 'cause it clicks the first button with the selector (.class2) but the problem is that there are many selectors with the same class than that one (They are children of (#id1)).
So its something like:
<div id="id1">
<div class="anything">
<a button class="class2"> </a>
</div>
<div class="anything">
<a button class="class2"> </a>
</div>
</div>
So this casper.click(".class2") is my problem I think. I need a way to select the current button on each iteration of the each function. Note that I can't use $(this).
CSS selectors provide the :nth-child() pseudo-class which you can use to select a child element based on an index. This works as expected when only .anything elements are children of #selector1goeshere.
You can use
casper.click("#id1 > :nth-child("+(index+1)+") > a.class2");
You can also use XPath expressions to do this which don't have that limitation of only having .anything children. For example like this:
var x = require("casper").selectXPath;
...
casper.click(x("//*[#id='id1']/*[contains(#class,'anything')]["+(index+1)+"]/a[contains(#class,'class2')]"));

jQuery toggle only working for the top element in the <ul>

I'm trying to implement the jQuery toggle item in my Rails 3.2.1 app.
I would like the toggle to work for each individual <li> item on the <ul>, so I can target which element to hide/show individually. But for some reason, only the top element has the toggle effect; the rest are not responding.
Here's the jsFiddle.
Can anyone explain why this is happening?
It’s because your divs all have the same id, which is invalid HTML. Since the DOM is only expecting there to be one element with any given ID, then when you write $("#trigger"), it only selects the first one it finds. Change the ID to a class.
<div class="trigger"> ...
And change your ID selector to a class selector.
$('.trigger').click(/* ... */);
jsFiddle
ID attributes must be unique on the page. Change all the id="trigger" to class="trigger" then try:
$(".trigger").click(function (){
$(this).find('.menu-item').toggle();
});
JSFIDDLE
$(".trigger").click('.menu-item', function () {
$(".menu-item", this).toggle();
});
Multiple elements with the same id is invalid HTML, and jQuery will only target the first that it finds with that id.
I updated your fiddle to use a class instead of ids
<div id="trigger" class="trigger">
Then:
$(".trigger").click(function (){
$(".menu-item", this).toggle();
});
to target the class and not the id.
Why do the elements have the same ids? An ID should be unique. If you want to select all the <li>s, use a CSS selector like $(".toggle-li").

How to get element by both id and class

Is there any alternative solution (in JavaScript) for document.getElementById(); to select a specific element, specifying both the class and id ?
for example I have such a content:
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="2"></div>
And I want to select the corresponding div under the "Question X" link in the function
function showQuestion(id)
{
var thediv = GetByClassAndId("q_content",id); // how to implement this function ?
WriteQuestionIn(thediv); //Ajax
}
Thanks in advance.
you can try document.querySelector()
like document.querySelector(".q_content#2") use the para like css selector..
Since ID is always unique (unless u make a mistake) u have no need to use both class and id to select the element.
Such an approach is not correct, and should be avoided at all cost.
What I suspect is your problem, is that the ID is only a number. Try adding a prefix which is a letter. Do view source to this page to see examples.
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="q1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="q2"></div>
function showQuestion(id)
{
var thediv = document.getElementById("q"+id);
WriteQuestionIn(thediv); //Ajax
}
Actually there is a function $ in jQuery for doing this operation. If you are using any framework, then you should remember there is always a jQuery library available. Else if you are using custom PHP, then add one of them like jQuery or other because they provide lots of types of selectors.
Now here is the code after adding jQuery:
$("#yourid") //basic selector
$("#yourid.yourclass").show()
Use .show() to show the selected element
Use .hide() To hide element

Categories