Pin .data/.attr to particular id and class - javascript

I am trying to pin some data or attr to the editButton class, but only to the element of the given thisId.
It works with only class but when I add thisId as a second parameter it stops working. I also tried to use .find() but it also doesnt work.
What I am doing wrong?
<a href="#!" class="editButton" id="{{$comment->h_id}}" onClick="editComment({{$comment->h_id}}, `{{$comment->f_text}}`)">
<script>
function editComment(id, text){
var thisId = "#" + id;
$(".editButton", thisId).attr("PinComment", "some new comment");
alert($(".editButton", thisId).attr("PinComment"));
}
</script>

$(".editButton", thisId) is equivalent to $(thisId).find(".editButton"); either of the would work if and only if the elements matching $(".editButton") are descendants of the element matching $(thisId).
However, from your code snippet, both $(".editButton") and $(thisId) are same elements, so your usage of $(".editButton", thisId) doesn't work as you expect.
Read this to understand the API you are using better.
To solve your problem, you could go with this approach:
var selector = ".editButton" + thisId;
var element = $(selector);
element.attr("PinComment", "some new comment");
alert(element.attr("PinComment"));

Related

Using createTextNode() but I need to add HTML tags to it (JavaScript/JQuery)

When I click an item in a table, I need it to add that item to a list and display that list.
Here's my code for adding/displaying the items in the list:
var myList = document.getElementById('my-list');
function addItemToList(id) {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(id));
myList.appendChild(entry);
};
This works great, but I also need to add a "delete" button to each item in the list.
But when I add + ' delete' to the createTextNode() parameter, it doesn't work. This is because, obviously, textNodes can only have plain text.
So how do I make this code work with the HTML tag? Is there any JS or Jquery method other than createTextNode() that will do the same thing, but allow HTML tags?
With the specific scenario you mention, you would just set innerHTML of the li
entry.innerHTML = id + ' delete'
Otherwise, either create the element like you did for the li, but using an a instead, and append it. Or just use insertAdjacentHTML() to append the whole thing
Creating the element
var entry = document.creatElement('li');
entry.appendChild(document.createTextNode(id));
var link = document.createElement('a');
link.href = "#";
link.innerText = "delete";
entry.appendChild(link);
Using insertAdjacentHTML
entry.insertAdjacentHTML('beforeend',id + ' delete');
Demo
var id = "Some Text";
var list = document.querySelector("ul");
var entry = document.createElement("li");
entry.insertAdjacentHTML("beforeend", `${id} delete`);
list.appendChild(entry);
<ul></ul>
Also since you tagged jQuery, you can do the same thing as insertAdjacentHTML but by calling jQuery's append() method
$(entry).append( id + ' delete' );
One possibility would be:
function addItemToList(id) {
var entry = document.createElement('li');
entry.innerHTML = id + 'delete';
myList.appendChild(entry);
};
I'm not sure if there are any particular reasons you're using createTextNode() or avoiding jQuery selectors, but if it's simply because you're new to jQuery overall, than this code snippet has some updates with better practices and solves your problem. Hope it helps!
var $myList = $('#my-list');
function addItemToList(id) {
var $deleteLink = $('Delete');
$deleteLink.on('click', function(e) {
e.preventDefault();
$(this).parent().remove()
})
var $entry = $('<li>'+id+'</li>')
$entry.append($deleteLink)
$myList.append($entry);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="my-list">
</ul>
Add Item

Move array of DOM elements to placeholders in page

I have a design received on my page with a set of placeholders such as:
<span id="ApplicationDate_" class="removeMe"></span>
Plus other many elements as well inside that html. These spans should be replaced by real inputs coming from another area on the page, such inputs look like:
<input type="text" id="ApplicationDate_48596977"/>
So basically what I need to do, is to get all input elements in an array, and then for each element, get its ID up to "_", and search for the span that equals that value, and replace it with this element, then remove all spans with class=removeMe, but I can't achieve it in code, below is what I have reached:
$(document).ready(function () {
var coll = $("input");
coll.each(function () {
var id = this.id; //getting the id here
var substringId = id.substring(0, id.indexOf('_') + 1); //getting the span id
this.appendTo("#" + substringId); //having problems here..
});
$(".removeMe").each(function () {
this.remove();
});
});
it tells me this.appendTo is not a function, any help or hint is much appreciated.
TL;DR - Just use:
$(".removeMe").replaceWith(function() {
return $("input[id^='" + this.id + "']");
});
Here's why:
this is a DOM element, but .appendTo() is a jQuery method. You probably just need to wrap this in a call to jQuery:
$(this).appendTo("#" + substringId);
That would place the <input> element inside the <span> like this:
<span id="ApplicationDate_" class="removeMe">
<input type="text" id="ApplicationDate_48596977"/>
</span>
But, then you call:
$(".removeMe").each(function () {
this.remove();
});
First, you would have the same problem as above - this is a DOM element, but .remove() is a jQuery method. Second, it would be better to just call $(".removeMe").remove() - wrapping it in a .each() is redundant. Third, that would remove the span, and the input along with it. That's not what you are trying to do is it?
If you want to replace the span with the input, use .replaceWith():
var coll = $("input");
coll.each(function () {
var substringId = this.id.substring(0, id.indexOf('_') + 1);
$("#" + substringId).replaceWith(this);
});
It seems like the whole thing could be rewritten, taking advantage of the attribute starts with selector, as:
$(".removeMe").replaceWith(function() {
return $("input[id^='" + this.id + "']");
});

js How to add href + text onclick

I need to pass (using javascript) text inside span to href
<div class='tableCell'><span>information</span></div>
<div class='tableCell'><span>contact</span></div>
<div class='tableCell'><span>about</span></div>
for example when i click to about link must be example.com/tag/about/
Here is my Answer. I'm using Javascript to manipulate the DOM to add a new element with the href equal to the inner text within the span element.
I hope you find this answer helpful.
Thanks.
var spans = document.getElementsByTagName('span')
var baseUrl = 'http://example.com/tag/'
for(var i=0; i<spans.length; i++)
{
var curElement = spans[i];
var parent = curElement.parentElement;
var newAElement = document.createElement('a');
var path = baseUrl+curElement.innerHTML;
newAElement.setAttribute('href', path);
newAElement.appendChild(curElement);
parent.appendChild(newAElement)
}
DEMO
The simplest way:
$( "span" ).click(function() {
var link = 'http://yousite.com/tag/'+ $(this).text().replace(/ /, "-")+"/";
window.location.href= link.toLowerCase();
});
DEMO
http://codepen.io/tuga/pen/yNyYPM
$(".tableCell span").click(function() {
var link = $(this).text(), // will provide "about"
href = "http://example.com/tag/"+link; // append to source url
window.location.href=href; // navigate to the page
});
You can try the above code
You do not have links but span in your html. However, you can get build the href you want and assign it to an existing link:
$('div.tableCell').click(function(){
var href = 'example.com/tag/' + $(this).find('span').text();
})
Lets work with pure javascript, I know you want to use jQuery but I am really sure too many people can't do this without looking in to web with pure javascript. So here is a good way.
You can follow it from jsFiddle
var objectList = document.getElementsByClassName("tableCell");
for(var x = 0; x < objectList.length; x++){
objectList[x].addEventListener('click', function(){
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML;
});
}
Lets work on the code,
var objectList = document.getElementsByClassName("tableCell");
now we have all element with the class tableCell. This is better than $(".tableCell") in too many cases.
Now objectList[x].addEventListener('click', function(){}); using this method we added events to each object.
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML; with this line if somebody clicks to our element with class: We will change the link to his first child node's text.
I hope it is useful, try to work with pure js if you want to improve your self.
Your Method
If you always are going to have the url start with something you can do something like this. The way it is set up is...
prefix + THE SPANS TEXT + suffix
spaces in THE SPANS TEXT will be converted to -
var prefix = 'http://example.com/tag/',
suffix = '/';
$('span').click(function () {
window.location.href = prefix + $(this).text().replace(' ', '-').trim().toLowerCase() + suffix;
//An example is: "http://example.com/tag/about-us/"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tableCell'><span>Information</span></div>
<div class='tableCell'><span>Contact</span></div>
<div class='tableCell'><span>About</span></div>
You can adjust this easily so if you want it to end in .html instead of /, you can change the suffix. This method will also allow you to make the spans have capitalized words and spaces.
JSBIN

how to get the value of an attribute using jquery

I need to get the attributes values of an element.
My code is as follows:
var vid=$('div.selected a');
var dataid=$(vid).data('vid');
var dataalid=$(vid).data('alid');
And HTML
<div class="vblock" id="selected">
<a class="video" data-alid="4" data-vid="4" href="resources/videos/xyz4.mp4">
I need to get the value of data-alid and data-vid of <a> tag. Please anyone help me....
You are almost there with what you have, but you've made a simple mistake. Your markup shows that the div has an ID of "selected", not a class, so you need to use an ID selector:
var vid=$('#selected a');
Notice that I've removed the div from the selector. That's because ID values must be unique within a document and there is therefore no need to qualify them.
Also, note that since $ will return a jQuery object, there is no need to pass vid to it again, which will be slower:
var dataid = vid.data('vid');
var dataalid = vid.data('alid');
trythis
var vid=$('div#selected a');
var dataid=$(vid).attr('data-vid');
var dataalid=$(vid).attr('data-alid');
you have a wrong selector for id.. and you don't need double $(...)
try this
var vid=$('div#selected a');
--------------^--- here this is id and not class
var dataid=vid.data('vid');
-----------^-- here
var dataalid=vid.data('alid');
Try this way, instead of '.' you have to use '#' because you are referring to an id and use .attr() to refer to your specific attribute
$(document).ready(function() {
var vid=$('div#selected a');
var dataalid = vid.attr('data-alid');
var datavid = vid.attr('data-vid');
});

JQuery replace html element contents if ID begins with prefix

I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,
<div id="rep_target">
Hello World.
</div>
would replace:
<div id="target">
Hrm it doesn't seem to work..
</div>​
I've tried:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});​
-and-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
​});​
Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
Related, but this is only text.
JQuery replace all text for element containing string in id
You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());
Option #2: Elements
$('#target').empty().append($('#rep_target').children());
If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides. You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
should do the trick. Hope that helps.
Get the id using the attr method, remove the prefix, create a selector from it, get the HTML code from the element, and return it from the function:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
Or simply:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});
From my question, my understanding is that you want to replace the id by removing the re-_ prefix and then change the content of that div. This script will do that.
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
Working Sample : http://jsfiddle.net/eh3RL/13/

Categories

Resources