How do I use the `data-text` attribute in an img element? - javascript

I'm trying to use the data-text attribute of html to assign text to an image, and then use the jQuery to pull the text from that image use it to alter a span element somewhere else. Does data-text work? It does not seem to be working on my code. Are there any alternatives?
Here is the jQuery code:
var target = $(".flex-active-slide img").attr("data-text");
$("#video_box_label").html(target);
Here is the html with the data-text attribute:
<li id="Abijah_Ayele_slide">
<img id="Abijah_Ayele_image" src="https://epwork.ep.corp/wg/ProdPayroll/Images_People/Abijah_Ayele.jpg" data-text="Abijah_Ayele">
</li>
<li id="slide2">
<img id="slide_image_2" src="https://epwork.ep.corp/wg/ProdPayroll/Images_People/Adil_Saleem.jpg" data-text="Adil_Saleem">
</li>

data-text is not an attribute with any special functionality. Attributes starting with data- prefix are custom attributes as w3schools says. You can use jQuery .data() function to manipulate this attribute.

you can add data- to many tags including <img>
It could be any text after the data- part (in your case you are using "text", but it could respectively be data-othertext or data-thirdtext - just reference it correctly later on (see below)).
You are using: <img id="slide_image_2" src="Adil_Saleem.jpg" data-text="Adil_Saleem">
In jquery you can access the data- like so:
$('#slide_image_2').data('text');
Put it in a var like so:
var dataText = $('#slide_image_2').data('text');
Now dataText value is Adil_Saleem.
And you could then manipulate data as you require.
If you are looking to add it as html of a <span>, it may look like:
HTML: <span id="myspan"></span>
jQuery: $("#myspan").html(dataText);

$('img').each(function(){
var $t = $(this);
console.log($t.attr('data-text'));
// Or if you want to append it to an element you already have
$('element').html($t.attr('data-text'));
}

Related

How add ID to HTML href with javascript

I have an HTML like this
<div class="this">
EXP
</div>
I want to add id to <a>. But do not know what to do.
First select your element using something like .getElementsByClassName(). Keep in mind that .getElementsByClassName() returns a NodeList collection of elements, so you'll want to access the first index (or loop over them). You can then simply set the ID with .id, as the ID is merely a property of an element.
This can be seen in the following:
const element = document.getElementsByClassName('this')[0];
element.id = 'element';
console.log(element);
<div class="this">
EXP
</div>
If you want to add this with Javascript, you'll need to use a selector to target your <a> tag and then set the id attribute on it. You can do this by using the querySelector() function or as seen below:
// Find an <a> tag that occurs below a class called "this" and set its id attribute
document.querySelector('.this > a').id = "some-id";
There are many other available functions to handle this through native Javascript and other frameworks, so your milage may vary depending on what you are using.
Example
In this example, we have provided some CSS that should only apply to an element with an id of "test" and we'll run the necessary code to show that the id is being added to the element (as it will be red):
document.querySelector('.this > a').id = 'test';
#test { color: red; }
<div class="this">
EXP
</div>
Add the id attribute to the <a> tag. See the differences of the middle line:
<div class="this">
<a id="expid" href="exp.com">EXP</a>
</div>

Change attribute type

Is it possible to change the attribute type of an element? Scrathing my head about this - all I can find is how to change the value of an attribute.
I want to change href to src on the element above. I have a script that change the element type to an iframe for mobiles, and I need the attribute to be a src type for it to work.
<a class="colorbox cboxElement" href="http://example.com">Diablo</a>
Is this possible?
Use removeAttr() method to remove an attribute and attr() method to set an attribute.
$('.colorbox').attr('src', function() {
return $(this).attr('href');
}).removeAttr('href');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="colorbox cboxElement" href="http://example.com">Diablo</a>
With pure Javascript use Element#setAttribute method to set attribute where you can get attribute value using Element#getAttribute method and remove an attribute using Element#removeAttribute method.
var ele = document.querySelector('.colorbox');
ele.setAttribute('src', ele.getAttribute('href'));
ele.removeAttribute('href');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="colorbox cboxElement" href="http://example.com">Diablo</a>
FYI : The jQuery method would work for multiple elements, in Javascript you need to iterate over the element collection to update multiple.
For eg:
// for older browser use [].slice.call(....).forEach
Array.from(document.querySelectorAll('.colorbox')).forEach(function(ele){
// do the rest here
})
Yes, You can change any attribute.
Use:
element.setAttribute(attribute_name, attribute_value)
and to get the value of attribute use
element.getAttribute(attribute_name)
Note that not every attribute is going to have an effect on element.
For example, setting type attribute on input element is going to create input of given type, but setting it on span does nothing.
If You want to hold some data information in attributes, I would recommend to use dataset API
If you wanted to use just javascript, you could get the attribute using getAttribute, set the new attribute using setAttribute, and remove the old attribute using removeAttribute.
var tag = document.getElementsByClassName('cboxElement')[0];
tag.setAttribute('src', tag.getAttribute('href'));
tag.removeAttribute('href');
<a class="colorbox cboxElement" href="http://example.com">Diablo</a>

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.

Custom attribute Not fetchable from li

I have following Code/Structure, what I am trying to do is to hide a div if a custom attribute matches. The problem at the moment is that I can't get the custom attribute as demonstrated in this code:
var elementToHide = 'file_type';
jQuery('#search-img-ctrl').each(function() {
var locationli = jQuery(this).find('li').attr(elementToHide);
alert(locationli);
alert(elementToHide); // I can't get the custom attribute
if (locationli != elementToHide) {
jQuery(this).find('.search-img-box').hide();
} else {
jQuery(this).find('.search-img-box').show();
}
});
And following is my HTML Structure.
<div id="search-img-ctrl" class="search-img-ctrl">
<div class="sampages" style="display: block;">
<div class="search-img-box sampageitems">
<a href="image_detail.php">
<img id="imageimage_array" width="277" height="206" src="upload/2014-05-02-14-05-512014-04-08-14-04-40000560_d.png" alt="">
</a>
<br>
<ul>
<li> Name </li>
<li>upload/2014-05-02-14-05-512014-04-08-14-04-40000560_d.png</li>
<li>identity </li>
<li>Modify</li>
<li latitude="null">Latitude</li>
<li>null</li>
<li longitude="null">Longitude</li>
<li>null</li>
<li model="null">model</li>
<li>null</li>
<li file_type="png">model</li>
<li>png</li>
<li> Image Size </li>
<li>11Kb</li>
</ul>
</div>
</div>
Ideally under html5 you should suffix your custom attributes with data- prefix. However, in your code to find the li that has specific attribute, use:
var locationli = jQuery(this).find('li[' + elementToHide + ']');
Here is a JSFiddle demonstrating this: http://jsfiddle.net/wANxV/
The main wrapper have id and class same value. This is not a good.
Put a numer or other after your id value (id="search-img-ctrl-1" etc) , then do each cycle on class not on id
JQuery.each('.search-img-ctrl');
Put attributes in your markup with 'data' prefix (as Satpal said) and other thig you can use directly the selector
var locationli = jQuery(this).find("li["+elementToHide+"]");
This code reads the attribute of the first found element, but it does not filter on it:
var locationli = jQuery(this).find('li').attr(elementToHide);
A filter might look something like this:
var locationli = jQuery(this).find('li')
.filter(function(){
return $(this).attr(elementToHide);
});
But obviously closure's method is much shorter. And keypaul is right, using data- prefix is the right way to store your own metadata on elements.
the answers to use li[' + elementToHide + '] are good ones, but to help you understand what you are experiencing
let's break down this line of code:
var locationli = jQuery(this).find('li').attr(elementToHide);
as you know, jQuery(this).find('li') returns all of the decendants of this which are li's, and in your example, there are 14 of these.
What does .attr() return when applied to a set of 14 elements?
I guess it could return an array, a concatenation, who knows?, but the writers of jQuery decided to just return the attribute corresponding to the first element in the set. In this case, you are calling .attr(elementToHide) on <li>Name</li>. This element does not have the "file_type" attribute, therefore, you get an empty string in return.
Here's a quick fiddle to illustrate: http://jsfiddle.net/pmn4/B9bqK/
to solve your problem, use either the techniques described by #keypaul and #closure or use jQuery's filter method

Storing data in html dynamically (html5)

I am creating a dynamic div in html which consists of multiple checkboxes. All these checkboxes and divs are being dynamically added to the html. I need to store some data about each div in the html to be accessed by javascript later. Can anyone show me an example where data can be added and retrieved dynamically in a div? I know HTML5 allows it and there are some other hacks to do it, but I am having trouble with syntax I guess.
Try to do it using JavaScript:
SomeClass.someVariable = document.getElementById('divid');
Otherwise if you mean to access custom data that has to used as attribute in your HTML tags then use
data-XXX = 'YYY';
And access it with JS:
document.getElementById('divid').dataset.XXX;
This post explains data-* attributes.
You can create custom attributes within your divs like this:
<div id="div1" data-text="Hello. This is a custom attribute."></div>
Notice the data- prefix. this is absolutely necessary.
Then (using jQuery) you can access the custom attribute:
$('#div1').data('text'); => "Hello. This is a custom attribute."
So using this you can do stuff like:
if($('#div1').data('text') != "FreddieBobman"){
alert("HI!");
} else {
alert("Forever Alone!");
}
The above example will alert "HI!" because $('#div1').data('text') does not contain
FreddieBobman, it is in fact "Hello. This is a custom attribute."
To create these attributes use the following:
$('#div1').attr('data-name', 'value');
Our div with id of div1 now has another attribute, data-name, and the attribute has a value of value. Of course, you can change the value of attributes as well:
<div id="div1" data-text="Hello. This is a custom attribute."></div>
<script src="jquery.js"></script>
<script>
(function(){
$('#div1').attr('data-text', 'This is cool.');
}());
</script>
Now the div has data-text equal to "This is cool.", not "Hello. This is a custom attribute."
It is Obtain by the data attributes that you add dynamically to the elements ,And retrieve when you want !
SET Attribute :
var div = document.createElement('div');
div.setAttribute('data','my_data');
div.innerHTML = "I am a div";
document.body.appendChild(div);
GET Attribute :
div.getAttribute('data')
WORKING DEMO
you can use attributes for your html tags. Also, in html5 you can also use custom attributes
What you want is to add or retrieve data from div tags dynamically?
Using javascript function you can simply get corresponding div element using its id,
var container = document.getElementById('your_element_id');
Then you can add what you want.
var stringToAdd = "<p>something you want to add</p>";
container.innerHTML = stringToAdd;
Also you can use a different class with different features and set it as your div class.
you need to add your features inside style tag under your class name. Then,
var elementID = document.getElementById(ID);
elementID.className ="your_new_class_name";
or you can set attributes for your tag.
elementID.setAttribute('display','inline');
Using jquery with javascript,
var elementID = document.getElementById(ID);
$(elementID).replaceWith( "<p>something you want to replace</p>" );
using class name or id you can dynamically append content using,
var stringToAdd = "<p>something you want to add</p>";
$(".your_class_name").append(stringToAdd);
also you can remove whole element using,
$(elementID).remove();

Categories