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>
Related
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>
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'));
}
I am new in javascript.I am trying this below code to get href attribute.
Facebook
<script type="text/javascript">
function cheak()
{
var a= document.getElementsByTagName("a").getAttribute('href');
alert(a);
}
</script>
I know this is working by below code
document.getElementById("myid").getAttribute('href'); // if I use any id
But in tag I don't want to use any id or class. How can I get this attribute without using any id or class in a tag.
Preface: Below, I've answered the question of how to find an element without using an id or class, in the general case. But if you just want the element from within your cheak function, then Zain's answer is the correct way to do that (with minimal changes to your code; arguably more correct might be modern event hookup).
But in tag I don't want to use any id or class. How can I get this attribute without using any id or class in a tag.
You reach for the Swiss army knife of element selection: document.querySelector. With it, you can use any CSS selector that matches the element:
var href = document.querySelector("any selector here").getAttribute("href");
querySelector returns the first match in the document. (There's also querySelectorAll, which returns a list.) They're both supported in all modern browsers, and also IE8.
Since you have the full power of CSS selectors, you can use anything about the position of the element in the document to find it.
There's too little context in your question for a specific example, but for instance if it's the first a in the document:
var href = document.querySelector("a").getAttribute("href");
alert(href);
Facebook
Or using that onclick:
var href = document.querySelector("a[onclick='cheak()']").getAttribute("href");
alert(href);
Facebook
If you pass in this when calling the function. it will pass the element reference to your function and you can use it to get value of href:
Facebook
<!-- Note -----------------------------^^^^ -->
<script type="text/javascript">
function cheak(a) {
alert(a.href); // Gives you the fully-resolved URL
alert(a.getAttribute("href")); // Gives you the content of the `href` attribute (not fully-resolved)
}
</script>
the parameter data is the complete tag on which the function is called
Facebook
<script type="text/javascript">
function cheak(e)
{
e.preventDefault();
// var a= document.getElementsByTagName("a").getAttribute('href');
alert(e.target);
}
</script>
I have an anchor in my HTML. it has a page attribute with a value. So everytime it is clicked I use the page attribute value in my js. Now I want to set a style attribute with a background color to show that a certain a element is selected. So I have to select the element by page attribute and add a new attribute with a value to the a element.
How do I handle that?
With HTML like:
<a href='#' page='1'>Link 1</a><br />
you could do:
$('a[page=1]').addClass('selected').attr('test', 'hi!');
(i.e. better to change display using a css class [e.g. 'selected'] than the style attribute - but the attr call there shows how to add an attribute).
To select an element by attribute value, you can use this syntax:
$('[attribName="value here"]')
Where attribName should be replaced with attribute name such as name, title, etc.
To add a new attribute value, you can use the attr method.
Example:
$('[attribName="value here"]').attr('attribute name', 'attribute value');
And this is how you can change the background color:
$('[attribName="value here"]').css('background-color', 'green');
Note you should replace dummy attribute names and values as per your requirements.
Not sure what you're asking.. do you need to find the a elemenent with a certain value for "page" and change its background?
$("a[page='value']").css('background-color', 'color-code');
Suppose I have these divs:
<div class="hat" rel="cap">
<div class="hat" rel="pine">
<div class="hat" rel="mouse">
How do I use JQuery to do a "where"?
For example
$("div.hat").remove WHERE rel="mouse"
Use the Attribute equals selector:
$('div.hat[rel=mouse]').remove()
You should be able to use the attribute selector:
$("div.hat[rel]") // to get all <div class="hat"> tags with a rel attribute
$('div.hat[rel="mouse"]') // to get a <div class="hat"> tag with a specific rel attribute
Use one of the attribute selectors such as the Attribute Equals Selector for this type of selection. For example:
$('div.hat[rel=mouse]').remove();
There are a number of other variations of the attribute selector to do things like matching an element whose attribute begins with, ends with, or contains a certain value. Check out all the Attribute Selectors at the jQuery API and familiarize yourself with them.