Set id from variable for each item - javascript

Trying to apply an anchor based on child and then create the ID for the anchor with same value. First half, the anchor, is working.
Applying this
$(".horizontal-tab-button a").each(function() {
var anchorid = $(this).attr('href', '#' + $(this).children('strong').html().replace(/ /g,"_").toLowerCase());
$(".horizontal-tab-button a strong").attr('id', anchorid);
});
To this
<li class="horizontal-tab-button">
<a href="#">
<strong>Application</strong>
</a>
</li>
Gives
<li class="horizontal-tab-button">
<a href="#application">
<strong id="[object Object]">Application</strong>
</a>
</li>
The error is [object Object], it should be <strong id="application">
.attr('id' + anchorid); doesn't give anything.
Live example https://jsfiddle.net/qyr0xk1e/1/

When you use .attr() to set an attribute it returns a jQuery object, not the attribute string. Just store the attribute in a variable and then use it to set the attributes.
$(".horizontal-tab-button a").each(function() {
var anchorid = $(this).children('strong').html().replace(/ /g,"_").toLowerCase();
$(this).attr('href', '#' + anchorid).find('strong').attr('id', anchorid);
});

This is because your variable is actually executing a method.
var anchorid = $(this).attr(...);
Try this instead:
var anchorid = $(this).children('strong').html().replace(/ /g, "_").toLowerCase();
$(".horizontal-tab-button a strong").attr('id', anchorid);
$(".horizontal-tab-button a strong").attr('href', '#' + anchorid);
// don't forget to actually reassign the href, since it has now been moved out of the variable

$(this).attr(...) doesn't return the value of the attribute. It returns jQuery.
So when you do this:
var anchorid = $(this).attr('href', '#' + $(this).children('strong').html().replace(/ /g,"_").toLowerCase());
anchorid is jQuery, not "application". Which you then set as the id on your strong element, hence the stringified object: [object Object]

Related

Splitting an href and putting the html into a variable

I want to send this HTML, minus "/modal" into a variable:
<span class="detailsLink"><object>DETAILS</object></span>
How can I add to this line to make it work?:
var eemailDetails = $('.detailsLink').html();
This ends up taking out /modal before it passes it into the variable:
var eemailDetails = $('.detailsLink a').each(function(){
this.href = this.href.replace('/modal', '');
}).html();
Thank you for your time!
The replacement should be made on the value retrieved instead of on the element's attribute.
So to retrieve the HTML markup including the targeted element, the outerHTML property can be used.
// Get the whole HTML
var eemailDetails = $('.detailsLink')[0].outerHTML;
// Remove /modal
eemailDetails = eemailDetails.replace('/modal', '');
console.log("The attribute unchanged: "+$('.detailsLink a').attr("href"));
console.log("The HTML retrieved: "+eemailDetails);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="detailsLink"><object>DETAILS</object></span>
So the each works fine, and I save the variable as a data-attribute on the element itself. Later, when it gets clicked, I can recall that data attribute as needed. Hope this helps!
$('.detailsLink a').each(function(){
var changedLink = this.href.replace('/modal', '');
$(this).data("changedLink", changedLink)
});
$(".detailsLink a").on("click", function(event){
event.preventDefault();
var returnEl = $(this).parents(".detailsLink").clone();
returnEl.find("a").attr("href", $(this).data("changedLink") );
console.log(returnEl[0].outerHTML );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="detailsLink"><object>DETAILS</object></span>
<span class="detailsLink"><object>More DETAILS</object></span>
<span class="detailsLink"><object>Yet More DETAILS!</object></span>

jQuery replaceWith() for HTML string

I am using filter() to select a list of elements then trying to replacing them by use of replaceWith(). The html is saved as string on a variable. It seem the replaceWith() is not working for me. When I log the variable content it shows the original string.
Is I know js objects are references. So, I was under the impression that replacing the selection will also replace element inside the string.
Here is the code
var content = '<div class="feature-box" contenteditable="false" data-sh-attr="%20title%3D%22jhk%22%20width%3D%224%22%20icon%3D%22thumbs-up%22" data-sh-content="kj"><div class="btn-panel"><a class="delete" href="#"><i class="fa fa-trash"> </i></a> <a class="edit" href="#"><i class="fa fa-pencil"> </i></a></div><div class="feature-icon-container"><i class="fa fa-thumbs-up main-icon"> </i></div><div class="feature-content"><h3>jhk</h3><div class="content">kj</div></div><div> </div></div><p>[block background_color="red" color="white"]Content of the block[/block]</p><p>This is an example page. It\'s different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say something like this:</p><blockquote><p>Hi there! I\'m a bike messenger by day, aspiring actor by night, and this is my blog. I live in Los Angeles, have a great dog named Jack, and I like piƱa coladas. (And gettin\' caught in the rain.)</p></blockquote><p>...or something like this:</p><div class="feature-box" contenteditable="false" data-sh-attr="%20title%3D%22kk%22%20width%3D%224%22%20icon%3D%22thumbs-up%22" data-sh-content="kk"><div class="btn-panel"><a class="delete" href="#"><i class="fa fa-trash"> </i></a> <a class="edit" href="#"><i class="fa fa-pencil"> </i></a></div><div class="feature-icon-container"><i class="fa fa-thumbs-up main-icon"> </i></div><div class="feature-content"><h3>kk</h3><div class="content">kk</div></div><div> </div></div><blockquote><p>The XYZ Doohickey Company was founded in 1971, and has been providing quality doohickeys to the public ever since. Located in Gotham City, XYZ employs over 2,000 people and does all kinds of awesome things for the Gotham community.</p></blockquote><p>As a new WordPress user, you should go to your dashboard to delete this page and create new pages for your content. Have fun!</p>';
jQuery(content).filter('.feature-box').each(function(){
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
var shortcode = '[feature' + attr + ']' + content + '[/feature]';
$this.replaceWith(shortcode);
});
console.log(content);
jsFiddle to play with
http://jsfiddle.net/du8d45tt/
You are creating an dom structure and is modifying that dom structure, which won't modify the original string
To get the updated html, you need to get the updated content of the dom structure.
var $tmp = $('<div />', {
html: content
})
$tmp.find('.feature-box').each(function () {
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
var shortcode = '[feature' + attr + ']' + content + '[/feature]';
$this.replaceWith(shortcode);
});
var replaced = $tmp.html()
console.log(replaced);
Demo: Fiddle
You don't actually assign the updated html anywhere. $this.replaceWith(shortCode); updates $this not content.
You can use .html() to get the updated content and assign it back.
content = $this.replaceWith(shortcode).html();
Due to the asynchronous nature of the jQuery each method, it runs a callback, you should also have the console.log within the each function.
jQuery(content).filter('.feature-box').each(function(){
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
var shortcode = '[feature' + attr + ']' + content + '[/feature]';
content = $this.replaceWith(shortcode).html();
console.log(content);
});
Strings are immutable objects in JavaScript, so you need to overwrite it with another value:
content = jQuery('<div>', {html: content})
.find('.feature-box')
.replaceWith(function() {
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
return '[feature' + attr + ']' + content + '[/feature]';
})
.end()
.html();
This also uses .replaceWith(fn) syntax as a handy shortcut for .each() and using .replaceWith() inside.

add dynamic id to links using Javascript?

I have many links on a page generated dynamically. Now I want to attach ids to them based on a link just before them.
I have written the following function to return me the value I want to add as id to the href I want.
<script>
function movingid(){
var res = location.href.replace(/.*student\/(.*)\/subject/, '$1');
var subjectid = res.split("/")[2];
var classid = res.split("/")[1];
var sectionid = res.split("/")[0];
return classid+"-"+sectionid+"-"+subjectid;
}
</script>
So what I did is
<a href="javascript:void(0);" id= "javascript:movingid();" >Move To</a>
But the HTML thus generated is not calling the function. Instead its adding the id as plain text form like this id= "javascript:movingid();". How can I call the function?
Please help
Create the links this way:
<a href="javascript:void(0);" id= "" >Move To</a>
Maybe wrapping the links with a div, which gets the id "mylinks". After this call a function adding the id with this code:
i = "1";
$( "div#mylinks a" ).each(function( index ) {
$(this).attr("id",i);
i++;
});
Instead of i take your code from the movingid function you already posted.

Get value from an attribute using JQuery

I have a table in my page that contains many rows, each row has an image which has an <a href> this <a href> has two attributes class and data-delete-id, so I have a multiple <a href> that has the same attributes and the same value for class.
each <a href> has a different value for the data-delete-id attribute.
In my JavaScript I have this code :
<script>
$(function() {
$('.deleteButton').confirmOn('click', function(e, confirmed){
// get jquery object access to the button
var $thisButton = $(this);
// this gets that data directly from the HTML
var id = $thisButton.data('delete-id');
if(confirmed) {
alert("<?php echo site_url('users/deleteUser')?>" + '/' + id);
}
});
});
</script>
So when I click on some <a href> that function well be fired, and it gets the id value from the data-delete-id attribute.
The problem is that id value it's always the value for the first <a href> in my HTML code.
I only want to get the value for the data-delete-id attribute for the clicked <a href>.
How can I do that ?
I checked the code for confirmOn here and it does not seem to register with each item in a set of selected elements. This is a bug with the plugin, but a workaround would be to wrap the whole thing in an each.
$(function() {
$('.deleteButton').each(function() {
$(this).confirmOn('click', function(e, confirmed){
// get jquery object access to the button
var $thisButton = $(this);
// this gets that data directly from the HTML
var id = $thisButton.data('delete-id');
if(confirmed) {
alert("<?php echo site_url('users/deleteUser')?>" + '/' + id);
}
});
});
});

Get attr(id) with a known href variable

I want to get the id name thanks to a href value that is set in a variable.
To do this, I want to:
get the attr('href') of a clicked element (that works).
put it in a variable (OK).
search this href in a every class called ".link" (not in #prev-ajax, #next-ajax id) (problem)
Get the parent id.
I tried this :
$('#prev-ajax,#next-ajax').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
$(".link[href*= href ]:not('#prev-ajax,#next-ajax')");
var ajax = $(this).parents('.element').attr('id');
alert(ajax);
});
As you're using a JavaScript variable, you need to escape the quotes. Also, don't wrap items in the :not selector in quotes.
Try this:
$(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
Edit: Looking at your fiddle, you're also not doing anything with that selector. See this:
$(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
var ajax = $(this).parents('.element').attr('id');
It should be:
var link = $(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
var ajax = link.parents('.element').attr('id');
Demo: http://fiddle.jshell.net/UKyT4/1/

Categories

Resources