Attributes in JQuery - javascript

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.

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>

How to find all elements that contain a certain attribute in Javascript?

Consider the following code
<button az-name="btn1">A sample button</button>
<p>A sample text</p>
<p az-name="p1">Another sample text</p>
Now I have to get reference to the button element and the 2nd paragraph element. How can I accomplish this in Javascript or jQuery?
With Jquery you can use the attribute selector, as follows:
Either, to find the p/button with the particular attribute:
$button = $("button[az-name]");
$parag = $("p[az-name]");
Or, to find any tags with the particular attribute:
$button = $("[az-name='p1']");
$parag = $("[az-name='btn1']");
Or mix the both solutions.
Note that you can use also that :
Attribute Contains Selector [name*="value"]: Selects elements that have the specified attribute with a value containing the a given substring
like this :
$all_az = $("[az-*='btn1']");
To get all tags which have an attribute begining with "az-" for example.
You can use
$("[az-name]")
For tweaking- plunker
For reference - attribute selector

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>

How to replace all id from href?

I have the following markup
<div class = "general">
<div id ="custom"></div>
</div>
How to change id = "custom" in all <div> with class="general" from href on page using jQuery?
You can try this:
$("div.general").each(function() {
$(this).children("div#custom").text($(this).children("a").attr("href"));
});
If I understand you correctly, you want to iterate through all div.generals, and change the text of each child div#custom to the href of the child a.
See a working example on JSfiddle.
Also, another tip is to avoid using multiple elements with the same id. In your code you have a <div> with id="custom". You also say that the div.general appears multiple times — therefore, the id "custom" will appear multiple times. This is bad practice. I suggest that you change id to class.
You need to loop through all div.general and replace the id attribute of div#custom to whatever is there as the anchors href property. The following code will work:
$(".general").each(function(){
$(this).find("#custom").attr("id", $(this).find("a").attr("href").replace("#", ""));
})
Here the .find() will dig out elements from any depth inside the parent. If you are sure about the DOM position of the elements, you can change the .find() to .children()

looping through elements jquery selector

I have to select elements which contains id attribute and class attribute having 'child-of-' value and loop through the elements returned by the selector.
So far i could write:
$('.child-of-').each(function(){
...
});
This selects all the elements having class of child-of- including elements which does not have id also.
There are elements which has that class but does not have any id attribute.
so How can i select elements which has 'id' attribute and id has some value and also has class of child-of-. ?
For example
<div id="any1" class="child-of-"></div>
<div id="any2" class="child-of-"></div>
<div class="child-of-"></div>
Only the div having id attribute must be selected. ie the first two divs in the example. the third does not have id attribute value and hence should not be selected
You can use attribute selector.
$('.child-of-[id]').each(function(){
...
});
Fiddle
If your classes starts with child-of- you can use attribute starts with selector:
$('[class^="child-of-"][id]').each(function(){
...
});
$('[id].child-of-').each(function(){
...
});
You can use this selector:
$('#child-of-.child-of-').each(function(){
...
});
To get the attribute values you would use the attribute selectors:
$('[id*="child-of-"][class*="child-of-"]').each(function...
Substring attribute selectors - http://api.jquery.com/attribute-contains-selector/

Categories