how to get the value of an attribute using jquery - javascript

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');
});

Related

Pin .data/.attr to particular id and class

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"));

Get NaN instead of id value in jquery

I try to get element id using jquery, but instead of id I have a NaN, can anybody help me?
<button class="editResume" type="button" id="editResume1">Edit</button>
$(function () {
$(".editResume").click(function () {
var id = parseInt($(this).attr('id').substring(6));
alert(id);
});
});
You should use 10 instead of 6 since the number is staying at 10th index:
var id = parseInt($(this).attr('id').substring(10));
Fiddle Demo
Another alternative solution here is to apply regex:
$(function () {
$(".editResume").click(function () {
var id = parseInt($(this).attr('id').match(/\d+$/),10);
alert(id);
});
});
Fiddle Demo
var id = parseInt($(this).attr('id').substring(10));
But why do you want do it in this way?
If you want to append some (number or id of the table) in the attribute id always seperate it with some character (say -).
eg. id='editResume-1'. Then in jQuery.
var id = $(this).attr('id').split('-').pop() will give back your number. It works for every case even if you id is id='edit1Resume-1 or id='5-edit-resume-1 or any. Remember to append your required number/id at the end seperated by -
I always prefer this way. May be useful (yn)
If only the number from id value changes you can get it by using
var id = parseInt($(this).attr('id').substring(10));
'editResume1'.substring(6) is actually 'sume1'
You can use slice method also to get the digit if the number is always present at the end
var id = parseInt($(this).attr('id').slice(-1));
JsFiddle
You probably need 10 instead of 6 in substring(indexA[, indexB]) also you can give end index
Live Demo
var id = parseInt($(this).attr('id').substring(10));

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/

navigating the dom javascript specific tag

Here it is DOM structure:
<div id="some">
NOTHIS
NOTHIS
<h3 class="myclass">HELLO</h3>
</div>
How can I get the value of HELLO in javascript?
EDIT: Forgot, I have other anchor tags inside 'some', so I want strictly the anchor tag inside the h3's
EDIT2: Got it:
var n = document.getElementById('some').getElementsByTagName('h3')[0].getElementsByTagName('a')[0].innerHTML;
Thanks all!
var linkText = document.getElementById('some').getElementsByTagName('a')[0].innerHTML;
or if you have jQuery
var linkText = $('#some').find('a').html();
var anchor = document.getElementById('some').getElementsByTagName('a')[0],
yourText = anchor.innerText || anchor.textContent;
It's cross-browser, too. http://www.quirksmode.org/dom/w3c_html.html
Propagate down the DOM from your ID.
var s = document.getElementById('some').getElementsByTagName('h3')[0].getElementsByTagName('a')[0].innerHTML;
I would put an ID on the a myself.
var shouldEqualHello = document.getElementById('some').getElementsByTagName('h3')[0].getElementsByTagName('a')[0].innerHTML;
edit: fixed
to get to a single dom element with javascript, you need a way to uniquely identify it. the ideal approach is to give your element a unique id.
<a id="myAnchor" href="#" style="color:red;">HELLO</a>
then you can directly obtain a reference in script.
var myAnchor = document.getElementById('myAnchor');
or if you are guaranteed that your element is the only anchor element within the "some" id you can do
var someDiv = document.getElementById('some');
var anchors = someDiv.getElementsByTagName('a'); // returns a list of anchor elements
var myAnchor = anchors[0]; // get the first element in the list
but since that's not the case you'll have to pick your way down through the dom some more.
var someDiv = document.getElementById('some');
var headers = someDiv.getElementsByTagName('h3');
var myH3 = headers[0];
var anchors = myH3 .getElementsByTagName('a'); // returns a list of anchor elements
var myAnchor = anchors[0]; // get the first element in the list
from there you can see the stuff between the tags with
alert(myAnchor.innerHTML);
or
alert(myAnchor.firstChild.nodeValue);
or some other method already mentioned here.
You could simply use query selector,
let result = document.querySelector('#some h3 a').innerText;
console.log(result);

How to get the first inner element?

So I want to get the first <a> tag in this <div>. This is really driving me nuts. Thanks for any help.
HTML
<div id="PGD" class="album" onmouseover="load(this)">
<a class="dl" href="#">DOWNLOAD</a>
</div>
Javascript
function load(dl)
{
var ID = $(dl).attr('id');
var elemnt = $('ID:first').attr('id');
}
Non-jQuery: (was not tagged with jQuery before, so I included this)
If you want to get the first child element only:
var element = document.getElementById('PGD').children[0];
If you want to get the first anchor element:
var element = document.getElementById('PGD').getElementsByTagName('a')[0];
With jQuery:
var element = $('#PGD').find('a:first');
// or, to avoid jQuery's pseudo selecors:
// var element = $('#PGD').find('a').first();
and actually your function can just be
function load(dl)
{
var element = $(dl).find('a:first');
}
Update:
As you are using jQuery, I suggest to not attach the click handler in your HTML markup. Do it the jQuery way:
$(function() {
$("#PGD").mouseover(function() {
$(this).find('a:first').attr('display','inline');
alert($(this).find('a:first').attr('display'));
});
});
and your HTML:
<div id="PGD" class="album">
<a class="dl" href="#">DOWNLOAD</a>
</div>
​See for yourself: http://jsfiddle.net/GWgjB/
$("#PGD").children("a:first")
This will give you the first child "a" tag, but not the descendents. E.g.
<div id="log">
<p>Foo</p>
Hello
Hello
</div>
Will give you : Hello
$(ID).find(':first')
See find jQuery command.
$('#PGD').find('a:first')
Actualy I've not understanding problem, so I'm trying correct your function, to make it clear for you:
function load(dl)
{
// var ID = $(dl).attr('id');
// var elemnt = $('ID:first').attr('id'); // Here is error-mast be like $(ID+':first')
var ID = $(dl).attr('id');
var elemnt = $(ID).find('*:first').attr('id');
}
I supose dl that is $('#PGD'). But child element A have not attribute id, what are you trying to find?
Also See: http://api.jquery.com/category/selectors/

Categories

Resources