How to add an HTML attribute with jQuery - javascript

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/.

Related

Javascript added attribute value not visible in view source

Javascript
var1.attr('title',vartit);
$(var1).attr('datetime',vartim);
Html
<time title="" datetime=""> </time>
I could successfully add the variable value in the respective html attributes but its not visible in view source.
I found some answers like innerHtml and all but they are for inside of time or div but not for html tag attributes, how can make that possible??
Thanks in advance
I don't know the whole context of the snippet you shared. But here you can find a working demo
The JavaScript part is just:
$(_ => {
$('h1').attr('datetime', '27-03-2017');
});
Then just look at the console to see the attribute.
If you want to use a jquery selector gor your "time" tag, it should be something like $('time').attr("yourattr",value). Try this and let me know if this works

Jquery onClick not Working by Class Name

Problem is actually pretty simple , but i don't know why can't i get it to work.
i want to add a classname to my button on Click by using its current class btn-cat.I am just a student learning not professional so please keep that in mind before make any acquisitions.
Here is the Link . where am i wrong?
Note: I can't find any good or valid way to post jsfiddle link that's why i shorten the link to workaround Here is SO question for that.
Change $('this') to $(this), otherwise you are passing to jQuery a string instead of DOM element in question. Demo - Fiddle

Cant get an attribute of an element with jquery

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")); });​

JQuery .attr won't retrieve or change values

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

Get values between DIV tags?

How do I get the values in between a DIV tag?
Example
<div id="myOutput" class="wmd-output">
<pre><code><p>hello world!</p></code></pre>
</div>
my output values I should get is
<pre><code><p>hello world!</p></pre>
First, find the element. The fastest way is by ID. Next, use innerHTML to get the HTML content of the element.
document.getElementById('myOutput').innerHTML;
document.getElementById("myOutput").innerHTML
innerHtml is good for this case as guys suggested before me,
If you have more complex html structure and want to traverse/manipulate it I suggest to use js libraries like jQuery. To get want you want it would be:
$('#myOutput').html()
Looks nicer I think (but I wouldn't load whole js library just for such simple example of course)
Just putting all above with some additional details,
If you are not sure about that div having some id is not there on html page then to make it sure please use.
var objDiv = document.getElementbyId('myOutput');
if(objDiv){
objDiv.innerHTML;
}
This will avoid any JavaScript error on the page.

Categories