Jquery how do we add custom attribute to <img> - javascript

I just want to add custom attribute to <img> tag which is created inside Jquery plugin....
this._image = L.DomUtil.create('img', 'leaflet-image-layer custom_image_class');
Above line creates <img> tag with the class name
`leaflet-image-layer custom_image_class`
I was able to add id attribute by adding
this._image.id = "my_image_id";
result is shown as,
<img src="" class="leaflet-image-layer custom_image_class" id="my_image_id">
everything works fine till above....
But now i want to add custom attribute "my_image" so that result should look like....
<img src="" class="leaflet-image-layer custom_image_class" id="my_image_id" my_image = "something">
how do we achive this?
I have already tried with attr , but no luck...

Note that inventing your own non-standard attributes (such as my_image) will mean that your HTML is invalid. Instead you should use data-* attributes. Try this:
this._image.dataset.my_image = "something";
Or if you want to use jQuery instead:
$(this.image).data('my_image', 'something');

use jquery attr
this._image = L.DomUtil.create('img', 'leaflet-image-layer custom_image_class');
this._image.id = "my_image_id";
$('#my_image_id').attr("my_image","something"); // add this line

Related

Add attribute to an object

How can I change the attribute of a tag in some HTML code given as an object?
Currently, if I do:
console.log(gallery.currItem);
I get:
So I then did:
console.log(gallery.currItem.html);
And I get the HTML in console (not as an object, I believe it's just as texy):
<video width="500" height="250" controls><source src="" type=""></video>
But I'm not sure how I would edit the video tag by adding the attribute muted="muted".
I tried:
console.log($(gallery.currItem.html).find('video'));
But this returned an object again. :/
I assume you are using PhotoSwipe. gallery.currItem.html is not a string but an actual html element.
You can just directly edit the attributes of it:
gallery.currItem.html.setAttribute("muted", "muted");
To make sure it's an actual element, if in question, do this:
if(gallery.currItem.html.tagname) {
gallery.currItem.html.setAttribute("muted", "muted");
} else {
// append it to the dom or wrap it into jquery and then set the attributes
gallery.currItem.html = $(gallery.currItem.html).attr("muted", "muted")[0];
}
try this.
$(gallery.currItem.html).attr("muted", "muted");
Answer:
$(gallery.currItem.container.lastChild).attr('muted', 'muted');

find & replace part of file path for 'src' attribute

Assuming I have a theme switcher, and there're multiple images/icons
<img src="images/icons/icon-1.png">
<img src="images/icons/icon-2.png">
<img src="images/icons/icon-3.png">
<img src="images/icons/icon-4.png">
And also I have another set of these icons with a different color/path
<img src="images/icons/blue/icon-1.png">
<img src="images/icons/blue/icon-2.png">
<img src="images/icons/blue/icon-3.png">
<img src="images/icons/blue/icon-4.png">
the below jQuery code working perfectly when I click to change theme color for 'once'
$('img').attr('src', $('img').attr('src').replace('images/icons', 'images/icons/blue'));
If I clicked again to choose another color say 'red', the path become like this
<img src="images/icons/red/blue/icon-1.png">
while it's supposed to be like this
<img src="images/icons/red/icon-1.png">
how I can make 'replace method' to find & overwrite old path WITHOUT change file name 'icon-1.png' for example, as it's a dynamic icons.
Thanks in advance.
Is the name always the same? in that case you can use the following code
$('img').attr('src', function(i, src){
return 'images/icons/blue/' + src.split("/").pop()
});
You need to loop and replace the src of each element.
$('img').attr('src', function(i, src){
return src.replace('images/icons', 'images/icons/blue')
});
When you use the getter version of .attr() it will return the attribute value of the first element in the matched element set, so the same value will get set for all elements.
Just get the filename from the source first, then rewrite the whole source. Assuming that you send as "theme" to changeTheme function, something from the following values: "images/icons", "images/icons/blue", "images/icons/red", etc. this will do the trick.
function changeTheme(theme) {
var img=$(img);
var filename=img.attr('src').split('/');
filename=filename[filename.length-1];
img.attr('src',theme+"/"+filename);
}
Or if you don't minde storing the file name as a data attribute to the image, you can change the second and third lines of the functions, with something along the lines of:
var filename=img.data("filename"); //assuming you are storing the file name in data-filename attribute

How to get the value from a string using javascript

I have a string like follows in javascript
var str='<img class="avatar avatar-small 012345" src="/img/staff_avatar_profile.jpg" /> olah blah';
I need to get every time the number like for this example 012345. Which will be ofcourse be different in different scenario and I also need to get the text olah blah which will be also different in different scenario.
I have the above string in a variable. ;)
How can i perform this in a efficient manner in java-script
The best way to parse HTML in a browser is to let the browser do it for you:
var div = document.createElement('div');
div.innerHTML = str;
var numbers = div.getElementsByTagName('img')[0].className.match(/ (\d+)/)[1];
Here's the fiddle: http://jsfiddle.net/CGuLC/1/
You could use jQuery if it works there to get an only numeric class name. Take a look at jQuery - selectors on a html string to get a clue.
Use the data attribute instead of class.
<img class="avatar avatar-small" data-id="012345" src="/img/staff_avatar_profile.jpg" />
Then use jQuery to get the data attribute.
jQuery('.avatar').data('id');
Sources:
http://html5doctor.com/html5-custom-data-attributes/
http://api.jquery.com/data/
If you need to store data for an element, one good way to achieve that is to use the data-key attribute with jQuery:
$('.avatar').data('number', '012345'); // set value
var number = $('.avatar').data('number'); // get value
The rendered markup will look like this:
<img class="avatar avatar-small" data-number="012345" src="/img/staff_avatar_profile.jpg" />

Get an attributes value of the ALT attribute of a hyperlink

My a-tag (link) contains innerHTML which is an image like this:
.innerHTML = <img alt="hello world" src="/Content/Images/test.png">
How can I get the text of the alt attribute with JQuery?
You really don't need jQuery. If you have the a element you can do this:
// lets call the anchor tag `link`
var alt = link.getElementsByTagName('img')[0].alt; // assuming a single image tag
Remember attributes map to properties (most), and unless the property is changed, or the attribute, the two should reflect the same data (there are edge cases to this, but they can be handled case-by-case).
If you truly do need the attribute there is
var alt = link.getElementsByTagName('img')[0].getAttribute('alt');
Last scenario is if you only have the image tag as a string.
var str = '<img alt="hello world" src="/Content/Images/test.png">';
var tmp = document.createElement('div');
tmp.innerHTML = str;
var alt = tmp.getElementsByTagName('img')[0].alt;
If you must use jQuery (or just prefer it) then the other answer provided by Alexander and Ashivard will work.
Note: My answer was provided for completeness and more options. I realize the OP asked for jQuery solution and not native js.
Being $a your <a/> element.
Using jQuery you can do:
$("img", $a).first().attr("alt");
Or, using pure JavaScript:
var $img = $a.getElementsByTagName("img")[0];
console.log($img.alt);
​
See it here.
use this.
var altName=$('a img').attr('alt');

jQuery: Using Selectors on HTML from an Attribute

I have some HTML that is stored as an attribute on a tag. I can access it in jQuery using
$("input[id$='_myField_hiddenSpanData']").attr("value")
This looks like this:
"<span id='spantest\user' tabindex='-1' contentEditable='false' class='ms-entity-resolved' title='test\user'><div style='display:none;' id='divEntityData' key='test\user' displaytext='Test User' isresolved='True' description='test\user'><div data=''></div></div><span id='content' tabindex='-1' contenteditable onMouseDown='onMouseDownRw();' onContextMenu='onContextMenuSpnRw();' >Test User</span></span>"
I would need the value of the key attribute (test\user). Can I somehow tell jQuery to parse a block of HTML and apply selectors to it? I found I can wrap it into a new jQuery object by wrapping it into another $(): $($("input[id$='_myField_hiddenSpanData']").attr("value")) but I still did not manage to apply a selector on it.
Any hints? And no, sadly I do not control the markup that generates the hidden field.
Wrap your crappy markup with a jQuery object, and then use the find function to apply a selector to it...
var crappyHtml = $("input[id$='_myField_hiddenSpanData']").attr("value");
var key = $(crappyHtml).find("div[key]").attr("key");
alert(key);
Try this:
var html = $("input[id$='_myField_hiddenSpanData']").attr("value");
var user = $(html).find("#divEntityData").attr("key");
alert("user=" + user);
You should be able to pass it as a context. Does this work?:
$('#divEntityData', $($("input[id$='_myField_hiddenSpanData']").attr("value"))).attr('key');

Categories

Resources