I'm trying to change HTML attributes using jQuery, but no matter what I do, I can't get anything to work with jQuery's .attr().
For testing, I've written
alert($("#logo").attr("title"));
and even though I have an img with id="logo" and a title, the alert remains blank.
My full method:
function switchVideo(videoID) {
var videoPlayer = document.getElementById("example_video_1");
videoPlayer.src = "video/Occam.webm";
videoPlayer.load();
$("#example_video_1").attr("poster", "video/ss.png");
//Doesn't work:
alert($("#logo").attr("title"));
$("#logo").fadeOut();
videoPlayer.play();
}
My fade out works, so I know I imported jQuery correctly.
I've gotten it working in another document, so there must be something else in the document messing it up. Does anyone know why this simple method won't work?
You can see the source page at http://jrstrauss.net/temp/create.html
Your div has the id logo, not the img.
Try:
$("#logo img").attr("title")
You should be using $.fn.prop for that now: http://api.jquery.com/prop/
You should use prop if you are using a recent version of jQuery.
You can also try this according to your HTML:
alert( $("#logo a img").attr("title") );
Demo
You have the following markup with id logo
<div id="logo">
......
</div>
Now, you are trying to run jQuery's .attr method by following code.
$("#logo").attr("title");
as you may know .attr method retrieves attribute value of the given element but that <div> doesn't have a attribute named title. so to confirm this, try retrieving attribute that does exist, for example id. so try this
alert($("#logo").attr("id"));
This will return the value of attribute. the important thing to note is jQuery looks for attributes of given element only, It doesn't scan child elements.
So, to make it work in your case. You need to do the following
alert($("#logo img").attr("title"));
Hope it helps
Related
I know jsFiddle displays it's results in an iFrame. I am taking a JS class right now and according to my instructor, "getElementById" is the most used function in all of JS.
So why doesn't "getElementById" work in jsFiddle:
document.getElementById("myH1")
However...
document.getElementsByTagName("H1")
Does work!
See my fiddle for the example:
http://jsfiddle.net/uM9t4/
document.getElementById("myH1") does work.
I think what you are trying to do is change the attribute of class from having "bye" to having "NO", which doesn't work. You are getting the class and changing it properly, but it is just a string. You have to then reassign it back to the class attribute.
document.getElementById("myH1").setAttribute('class', document.getElementById("myH1").getAttribute("class").replace("bye","NO"));
Or, stashing the element in a variable:
var myH1 = document.getElementById("myH1");
myH1.setAttribute('class', myH1.getAttribute('class').replace('bye', 'NO'));
it does, its just your thinking of how replace works is wrong, it does not do an inline change it returns the changed string, if it didnt work you would be getting an
Cannot call method 'getAttribute' of null
document.getElementById("myH1").getAttribute("class").replace("bye","NO");
should be
var change = document.getElementById("myH1").getAttribute("class").replace("bye","NO");
document.getElementById("myH1").setAttribute("class",change);
JSFiddle
I have got this html:
<img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt="">
I am trying to get this:
$('body').on('click','.hostPic',function(){
console.log($(this).attr('data-name'));
});
Whenever the picture is pressed, I want to gets its data-name attribute, but it doesnt work.. I get undefined reported when I try to retrieve the attribute. Any reason why?
Add the hostPic class to that image.
Additionally, you can just use .data('name'), but it doesn't actually make a difference. Older browser may have trouble with .data, but it's never been a problem for me.
$('.hostPic').click(function() {
console.log($(this).data('name'));
}
Make sure your image has the class 'hostPic' and then do the following in your jQuery:-
$('.hostPic').on('click', function() {
console.log($(this).data('name'));
}
The following code worked for me, maybe you are attaching the events wrong object, you can understand that by debugging the this object instead of data-name.
And another thing is if you are going to use .data just for read string you should use .attr as the .data caches and tries to convert the value its appropriate type like number or JSON it is a heavier process than .attr.
<img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt="">
$("img").click(function () { alert($(this).attr("data-name")); });
Below is the div that I want to alter
<div id="#page.Page" class="pageMessages" data-messages='#Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(#page.Messages))'></div>
I want to change the value of the message when a javascipt function is called from an external .js file. What is the correct way to do this?
Like So...
// This Performs the Change
$('#changeme').attr('data-messages', 'New Value');
// Show the Change
$('#changeme').html( $('#changeme').attr('data-messages') );
Here is a Working Fiddle
The one problem I see is the id='#page.Page' , this doesnt work.
I hope i get what you're trying to do, you can use jquery's change attribute for that
JQUERY
<script>
$(document).ready(function(){
$(".pageMessages").attr("data-messages","your-new-value-here");
});
</script>
DOC: http://api.jquery.com/attr/
So from the home page, i have a link that goes to a products listing page.
The product page has expand/collapse divs.
I need the appropriate div to expand depending on what the url# is.
So the link on the homepage is
healthy snacks
when i click the link above, i am trying to activate this, on the product page:
Healthy Snacks
I've tried some of the other codes that i found that trigger click by checking for hash tag and none of them were working properly, i think it's because of the ReverseDisplay js.
Please any insight would help.
thanks
You can make the following changes in the document ready function of your product page:
Simple fix: Since the jQuery id-selector is #elementId, you can simply use the window.location.hash value as your id selector, and use it to target the desired element.
if ( window.location.hash ) {
$(window.location.hash).click(); //clicks on element specified by hash
}
Better: In addition to the above, take the js out of your markup.
$('#healthysnacks').click(function(e) {
e.preventDefault();
ReverseDisplay('products4');
});
Then, after doing this, use the $(window.location.hash).click() code from above.
Also, change your link to:
Healthy Snacks
You can use the hash property of the Location object, try the following:
$(document).ready(function(){
var id = window.location.hash;
$(id).trigger('click')
})
As you are using jQuery instead of using javascript: protocol, you can use the jQuery click method:
$('#healthysnacks').click(function() {
// do something here
})
The answers suggested here are valid, but...
Be extremely careful when using the window.location.hash as it is in a jQuery selector because this could lead to a XSS vulnerability. $() can also create an HTML element and with a carefully constructed hash value, someone could execute arbitrary JavaScript code.
For example
http://my-website.com/about#'><img src=x onerror=alert(/XSSed/)>
If my-websites.com/about page uses the window.location.hash inside a jQuery selector, that onerror code would end up getting executed.
Well, I have this jQuery image slideshow that uses the attribute "control" inside an <a>. Seeing how it didn't validate I searched for a way to add this attribute inside my HMTL via jQuery but I didn't really find anything relevant. Now I don't really care about how valid my page is, but I'm really curious in how to add an HTML attribute inside an HTML tag.
In case I wasn't clear enough with my explanation, I have this code:
<a id="previous" control="-6" href="#"></a>
And I want to add control="-6" with jQuery.
Use jQuery's attr function
$("#previous").attr("control", "-6");
An example
// Try to retrieve the control attribute
// returns undefined because the attribute doesn't exists
$("#previous").attr("control");
// Set the control attribute
$("#previous").attr("control", "-6");
// Retrieve the control attribute (-6)
$("#previous").attr("control");
See this example on jsFiddle
You can alternatively use data function to store values on elements. Works the same way, for example:
$("#previous").data("control"); // undefined
$("#previous").data("control", "-6"); // set the element data
$("#previous").data("control"); // retrieve -6
Using data you can store more complex values like objects
$("#previos").data("control", { value: -6 });
($("#previos").data("control")).value; // -6
See a data example on jsFiddle
Since the jQuery version has been well covered here, I thought I'd offer something different, so here a native DOM API alternative:
document.getElementById('previous').setAttribute('control','-6');
Yes, I know you asked for jQuery. Never hurts to know the native way too. :o)
Let me see if I understood you.
You have, for example, the code:
<a id="previous" href="#"></a>
And by jQuery you want it to be:
<a id="previous" control="-6" href="#"></a>
Is it right?
If it is. You just have to do:
$('#previous').attr('control', -6);
If an attribute doesn't exists it's created by jQuery.
So, to remove it you can do:
$('#previous').removeAttr('control');
What you're doing doesn't respect the html rules and everything else, but it works fine, a lot of plugins do the same. ;D
I hope this could be helpful!
See you!
Try this:
$('#previous').attr('control', '-6');
Why? the $.attr(); function of jQuery allows you to add, get or update attributes (class, id, href, link, src, control and everything else!).
$("#previous").attr("control", "-6");
HTML:
<a id="previous" href="#">...</a>
jQuery:
$('#previous').attr('control', '-6');
jQuery's attr will do that. Example:
$("#previous").attr("control", "-6");
Also check out this example at http://jsfiddle.net/grfSN/.