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(){})
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 a javascript like this one
var funct = function(){
return {
init : function(data) {
this.sendRequest({
action : 'login'
});
},
login : function()
{
var parentDIV = $("#dnn_ctr450_HtmlModule_lblContent");
parentDIV.attr('href', 'https://webcenter.elendersolutions.com/webcenter/').trigger('click');
}
}
}
HTML CODE of this one.
<div id="dnn_ctr450_ModuleContent" class="DNN_HTMLContent">
<div id="dnn_ctr450_HtmlModule_lblContent" class="Normal">
<p></p>
<h2></h2>
<h2>
<a href="https://webcenter.elendersolutions.com/webcenter/" target="_self"> <-- how can i trigger this one?
<img width="188" height="40" border="0" src="/Portals/0/WebcenterSignin.gif" alt="Webcenter Login"></img>
</a>
</h2>
<h2>
<a href="https://rates.lsi-lps.com/">
<img width="188" height="40" border="0" src="/Portals/0/RateCalculatorSignin.gif" alt=""></img>
</a>
</h2>
<h2></h2>
<p></p>
</div>
what i'm trying to do is to trigger the link so it would function like i just click it manually.
For one thing, you aren't actually selecting the link correctly. Rather, you are selecting its parent div, and setting an href on the div. The target element of your function is what is in your jQuery object, in this case the div: $("#dnn_ctr450_HtmlModule_lblContent").
Instead, select the anchor link directly (it may be worth reviewing the jQuery docs for the attribute-equals selector and find:
var parentDIV = $("#dnn_ctr450_HtmlModule_lblContent");
var aLink = parentDIV.find("a[href='https://webcenter.elendersolutions.com/webcenter/']");
The second problem is that jQuery's click functionality won't allow you to follow links; you'll have to take advantage of the native html element's click method, as detailed in this SO post.
aLink[0].click();
Note that by doing [0] we are accessing the underlying DOM element, and so the method we're calling is not a jQuery method.
we can't do anything with it with JQuery. the only we can do is to progmatically do the redirection.
var href = parentDIV.attr('href');
window.location.href = href;
but with native javascript yes we can.
parentDIV.[0].click(); //where the index 0 returns the native DOM object.
but please be advised that for some reasons browsers doesn't want to trigger redirection from href link when triggered progmatically by javascript.
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>
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/
I'm having an issue with using Jquery toggle on a feed. I have a hyperlink called Tags. When i click on this it toggles a div underneath it.
It works - But only for the top post in the feed - If I have any other posts in the feed it doesn't work.
Below Is Jquery:-
<script type="text/javascript">
$(function () {
$("#hypfeedTagBtn").click(function() {
$("#divPostBodyTags").toggle();
return false;
});
});
</script>
Below is HTML:-
<div id="divPostFoot_64" class="dPostMain dPostFoot">
<span id="Content_ucFeeds_repFeedThread_lblFeedViewCouont_0" class="spFootReplyCount"></span>
<span id="Content_ucFeeds_repFeedThread_lblFeedShareLink_0" class="spFootLinks"></span>
<span id="Content_ucFeeds_repFeedThread_lblFeedDeleteLink_0" class="spFootLinks"></span>
<a id="hypfeedTagBtn" class="spFootLinksShowTags">Tags</a>
<a id="Content_ucFeeds_repFeedThread_hypFeedMessageMe_0" class="spFootLinks" href="/Mail/NewMessage.aspx?FeedID=64">Message Me</a>
</div>
<div id="divPostBodyTags" class="dPostMain dPostTAGSDIV" style="display: block;">
<ul id="PostBodyTags">
<li class="TAGLiItem">
<a class="TAGaItem">Plumbers</a>
</li>
<li class="TAGLiItem">
<a class="TAGaItem">Plumbers</a>
</li>
</ul>
</div>
Thanks
Steve
MDN element.id
The ID must be unique in a document, and is often used to retrieve the
element using document.getElementById.
In some documents (in particular, HTML, XUL, and SVG), the id of an
element can be specified as an attribute on the element like so: .
However you can't use this attribute in a custom XML document without
correctly specifying the type of the id attribute in the DOCTYPE.
Other common usages of id include using the element's ID as a selector
when styling the document with CSS.
Note that IDs are case-sensitive, but you should not create IDs that
differ only in the capitalization (see Case Sensitivity in class and
id Names).
Use a class instead of an id if you want to toggle more than one section.