I have a link. Like this:
I want remove this title and put the title text in a data attribute. As data-title. How can i make this with jquery.
So remove the title element. And place the text of the title element. In a new title data element.
Thanks
// you'd probably wanna give an unique id to your anchor to more easily identify it
var anchor = $('a');
var title = anchor.attr('title');
anchor.removeAttr('title');
anchor.attr('data-title', title);
// set title data-title to value of title
$("a").attr("data-title", $("a").attr("title"))
// clear title
$("a").attr("title", "");
Also I would give your link a class, so this action doesn't run on every a on the entire page.
Try:
$("a").attr("data-title", $("a").attr("title"));
$("a").removeAttr("title");
User attr method to set the attribute of element. And removeAttr method to remove the attribute
$("a").attr("data-title", $("a").attr("title"));
$("a").attr("title", "");
// or
$("a").removeAttr("title");
PS: Would suggest a unique id or a class for the anchor element
<a id="1" href="#" title="Title from this link 1"></a>
<a id="2" href="#" title="Title from this link 2"></a>
var t = $("a[title='Title from this link 1']").attr("title");
$("#2").attr("title", t);
jsfiddle link : http://jsfiddle.net/NEBh4/
you can see the changes happen to the links in the result window by using firebug or any other dev tool
$(document).ready(function(){
//example code one
var tempLink = $('#link');//cash the jquery object for performance
tempLink.attr('data-title', tempLink.attr('title')).removeAttr('title');
/*In above example I used an id to capture the html element, which mean u can only do above step only for one element. If you want to apply above step for many links you can use the following code. In this case I'm using a class name for the link element*/
//example code two
$('.link').each(function(){
$(this).attr('data-title', $(this).attr('title')).removeAttr('title');
});
});
HTML for the above example
<!-- for example code one -->
<a id="link" class="link" href="#" title="Title from this link"></a>
<!-- for example code two -->
<a class="link" href="#" title="Title from this link 1"></a>
<a class="link" href="#" title="Title from this link 2"></a>
<a class="link" href="#" title="Title from this link 3"></a>
Related
My html is
<a id='_requestOne' href='#applynow'> apply one </a>
<a id='_requestTwo' href='#applynow'> apply two </a>
<a href='#applynow'> apply three </a>
I want to change the anchor text for the second one alone. so I implemented in script as
$("a[href='#applynow']").text("request call");
Its changing all the three tags, so I tried as
$("#_requestTwo a[href='#applynow']").text("request call");
But its not working.
Can anyone give me a solution that how could I declare both id & href in same call.
Thanks in advance.
What you can do is target the second Item of the jQuery Object:
$( $("a[href='#applynow']")[1] ).text('request call') //starts counting at 0
I do not advise on this, it makes the code less maintenable if the html markup changes. You have an ID, so use that instead.
$("#_requestTwo").text('request call')
PS:
The reason why your second try doesn't work is because you had an error in the selector:
$("#_requestTwo a[href='#applynow']")
//should be
$("a[href='#applynow']#_requestTwo")
First select anchors with href then specify with ID or select directly by ID because ID should be unique:
$("a[href='#applynow']#_requestTwo").text("request call");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id='_requestOne' href='#applynow'> apply one </a>
<a id='_requestTwo' href='#applynow'> apply two </a>
<a href='#applynow'> apply three </a>
Always select elements from low to high specificity like:
$("tagname.class");
I have this code here in HTML:
<a class="cta" href="URL" target="_blank">TEXT</a>
What I try to achieve is to add a span tag inside the link tag, so that it would look like this:
<a class="cta" href="URL" target=_"blank"><span>TEXT</span></a>
I tried with prepend but it seems not to work for my case…
Using jQuery's .wrapInner( wrappingElement ):
$(".cta" ).wrapInner("<span></span>");
Description: Wrap an HTML structure around the content of each element in the set of matched elements.
The .wrapInner() function can take any string or object that could be passed to the $() factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around the content of each of the elements in the set of matched elements.
Source: https://api.jquery.com/wrapInner/
The .html( function ) is a good method for changing html content of element. Current html content of element setted in html variable in function that you can set it in new added child.
$("a.cta").html(function(i, html){
return "<span>"+ html +"</span>";
});
span { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="cta" href="URL" target="_blank">TEXT</a>
<a class="cta" href="URL" target="_blank">TEXT 2</a>
Use .wrapInner() in jquery
Description: Wrap an HTML structure around the content of each element
in the set of matched elements.
var con = $('.cta').text();
$(".cta").empty().wrapInner("<span>"+con+"</span>");
http://api.jquery.com/wrapinner/
try the following:
$('a.cta').each(function(){
var text = $(this).text();//take the text from the link
$(this).html($('<span>',{text:text}));//create a span tag and append the text in it after that use html to append the span to the link tag
});
$('a.cta').each(function(){
var text = $(this).text();//take the text from the link
$(this).html($('<span>',{text:text}));//create a span tag and append the text in it after that use html to append the span to the link tag
})
span { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="cta" href="URL" target="_blank">TEXT</a>
<a class="cta" href="URL" target="_blank">TEXT2</a>
<a class="cta" href="URL" target="_blank">TEXT3</a>
Replace the html():
$(function() {
$('.cta').html( '<span>'+$('.cta').html()+</span>' );
});
You have to get the content first and then replace the current to another that you made!
You can use a classe selector like $(".myClass") then replace the text by using the $(".myClass").html("<p>My new HTML content</p>"); method on the selected target:
$(document).ready(function() {
$(".cta").html("<span>" + $(".cta").html() + "</span>");
});
Here is a JSFiddle to see this in action
I am fairly new to javascript and just trying to figure out how to get 100's of image links to change to a specific image once they've been clicked.
I know you can add ID's, but having to make 100's or 1000's of ID's will be a pain. Maybe someone will be able to help me with this issue, or direct me in the correct direction. Thank you!
<a id="click"><img id="change" src="http://i.imgur.com/zS0lOud.jpg" onClick="window.open('http://yahoo.com','_blank');"></a>
<a id="click"><img id="change" src="http://i.imgur.com/zS0lOud.jpg" onClick="window.open('http://google.com','_blank');"></a>
<a id="click"><img id="change" src="http://i.imgur.com/zS0lOud.jpg" onClick="window.open('http://monster.com','_blank');"></a>
document.getElementById('click').onclick = function(){
document.getElementById('change').src = "http://i.imgur.com/0eaWvgw.jpg";
}
Using jQuery,
$('a').on('click', function() {
$('img').each(function() {
$(this).attr('src', 'http://i.imgur.com/0eaWvgw.jpg')
});
});
First of all, There must not be multiple elements in a document that have the same id value.
Use common-class over all the elements on which click event is to be bound
Use jQuery .on method to register events over all the elements having specified common-class
Also note that you have attached inline-click event over img elements, which action is suppose to take place once click is dispatched ?
$('.click').on('click', function(e) {
e.preventDefault(); //To prevent behavior of `a` elements
$(this).find('img.change').prop('src', 'http://i.imgur.com/0eaWvgw.jpg');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a class="click">
<img class="change" src="http://i.imgur.com/zS0lOud.jpg" onClick="window.open('http://yahoo.com','_blank');">
</a>
<a class="click">
<img class="change" src="http://i.imgur.com/zS0lOud.jpg" onClick="window.open('http://google.com','_blank');">
</a>
<a class="click">
<img class="change" src="http://i.imgur.com/zS0lOud.jpg" onClick="window.open('http://monster.com','_blank');">
</a>
As others stated, an id is something that must be unique. A class is what you want to use. The class attribute is a space-separated list of words. In this case, we only need one class on all links. Now you put some JS on all these links, but you should instead write it like this:
<a class="change" href="http://www.example.com" target="_blank">
<img src="image.png" />
</a>
The links will open the sites in a new window or tab even on browsers with JavaScript disabled in that way.
Then we need to retrieve a list of all elements with the "change" class, and add an event listener for the click event on all of them.
var changeLinks = document.querySelectorAll('.change');
var clickListener = function(e) {
var imgElement = e.currentTarget.querySelector('img');
imgElement.src = 'newimage.png';
// technically, the image is only changed once so we can remove the
// event listener once it has run on a link
e.target.removeEventListener('click', clickListener);
};
for(var i=0, element; element = changeLinks[i]; ++i) {
element.addEventListener('click', clickListener);
}
This question already has answers here:
How can I apply a jQuery function to all elements with the same ID?
(4 answers)
Closed 9 years ago.
I am using the "replace" function to remove all non-numeric values in a div.
It seems Jquery replace only affects the first element.
Here is my Jquery:
$('#comment').each(function() {
var thz = $(this);
var repl = thz.html(thz.html().replace(/\D+/g, ''));
});
HTML Code:
<a id="comment1" href="#"> c2fđf011. </a>
<a id="comment1" href="#"> c20ff113. </a>
<a id="comment1" href="#"> c201gf76341. </a>
Result:
2011 c20ff113. c201gf76341.
The result I want is:
2011 20113 20176341
You have duplicate ids, Which is invalid and also jQuery ID selector(or any other id selector like document.getElementById which internally jQuery uses because element with ids are indexed by most browsers and are meant to be unique) will return only the first one that appears in DOM. Change it to class and see it working:
$('.comment').each(function() {
var thz = $(this); var repl =
thz.html(thz.html().replace(/\D+/g, ''));
});
HTML
<a class="comment1" href="#"> c2fđf011. </a>
<a class="comment1" href="#">c20ff113. </a>
<a class="comment1" href="#"> c201gf76341. </a>
By the way had your id been like this:-
<a id="comment1" href="#"> c2fđf011. </a>
<a id="comment2" href="#">c20ff113. </a>
<a id="comment3" href="#"> c201gf76341. </a>
Starts with Attribute selector will help you (But slow you down literally, since this is an attribute selector and lose the advantage of using IDs).
$('[id^=comment]').each(function() { // While using this better give a container context $('[id^=comment]', 'container').each(function...
var thz = $(this);
var repl = thz.html(thz.html().replace(/\D+/g, ''));
});
Demo
Moral: IDs must be unique
ID in a HTML page is supposed to be unique
That is the reason it targets only the first instance of the element found.
Replace the elements with class instead
$('.comment').each(function() {
// Your code
});
$('.comment').each(function() { var thz = $(this); var repl = thz.html(thz.html().replace(/\D+/g, '')); });
replace ur element with id comment to a class comment.
If you use ID several times on elements the selector will only pick the first element with that ID.
But when you use class instead, the selector will pick all the element having that class.
If you really don't want to change the html you can use selector by attribute. But as others suggested, using class instead of id is the best option here.
$('div[id="comment"]').each(function(){})
got a simple question! i have a code with structure like that:
<a class="adv_link" target="_blank" href="">Link 1</a>
text here 1
<div class="adv_separator"></div>
<a class="adv_link" target="_blank" href="">Link 2</a>
text here 2
<div class="adv_separator"></div>
and etc...
i want to add BEFORE EACH link with class "add_link" the code: <div class="slide"> and add AFTER EACH div with class "adv_separator" the code: </div> how i can do it with jquery?
p.s. in other words i want to create several divs nested with these links,texts and divs so i can use jquery cycle plugin to create a slider.
thank you all for the help!
Simple logic, but you have to know how the DOM works. (Append "moves" the element, there is no "sparse selector", you need to know where to place the new element, etc.)
$('.adv_link').each(function() {
var el = $('<div></div>', {'class': 'slide'}),
link = $(this),
text = $(this.nextSibling),
sep = link.nextUntil('.adv_separator');
// Append each element. Cloned elements, of course.
el
.append(link.clone())
.append(text.clone())
.append(sep.clone());
// Remove the separator and the text.
sep.remove();
text.remove();
// And replace the link with the full div containing the cloned elements.
link.replaceWith(el);
});
The very short version:
$(".adv_link").each(function() {
$(this).nextUntil(".adv_separator +")
.andSelf().add(this.nextSibling)
.wrapAll("<div class='slide' />");
});
DEMO: http://jsbin.com/ukafip/2/