Get the href value using HTML5 data attributes - javascript

I would like to get the value of the href i.e. the web link using the data attribute.
I have the following snippet of code
<div class="my-item-details">
<h3 class="my-item-title" data-item_item="x12">
<a href="http://link.com">
My Classic Box
</a>
</h3>
<span class="my-item-price" data-item_item="x12">
38.00
</span>
</div>
The following 2 snippets give the right output.
var price_val = $('.my-item-price[data-item_uuid=x12]').text();
price_val = $.trim(price_val)
console.log(price_val);
38.00
var item_name = $('.my-item-title[data-item_uuid=x12]').text();
item_name = $.trim(item_name)
console.log(item_name);
My Classic Box
However when I run this code
var item_link = $('.my-item-title[data-item_uuid=x12]').attr("href");
item_link = $.trim(item_link)
console.log(item_link);
I get an empty string instead of http://link.com
What am I missing?

.my-item-title[data-item_uuid=x12] selects the h3 element, which doesn't have an href attribute.
Only the a element has that.
Add a descendant combinator and a type selector:
.my-item-title[data-item_uuid=x12] a

You are trying to get the attribute href from a <h3> element without href property:
You could make a change on your selector this way to get the correct result:
var item_link = $('.my-item-title[data-item_uuid=x12] > a').attr("href");
This should give you the correct value.

Related

Javascript: Select all data-qa attributes on HTML Page

Using only JavaScript, without the use of JQuery etc, what is the most efficient way to select all attributes names that have a certain data attribute (let's say data-qa).
<p data-foo="0"></p><br/><h6 data-qa="apple"></h6>
<p data-foo="0"></p><br/><h6 data-qa="book"></h6>
<p data-foo="0"></p><br/><h6 data-qa="car"></h6>
Expected result should be list :
apple
book
car
This question gets the parent elements, I want the attributes themselves. Select all elements with "data-" attribute without using jQuery
Resources:
Selenium find element via Data-Qa attribute
Data-QA Attribute: A better way to select elements for UI test automation
The code below works by getting all of the elements using document.querySelectorAll, mapping the elements to the values of the data attributes, and then filtering out the ones that are falsy or '0'.
let getAllDataAttrs = name => Array.from(
document.querySelectorAll(`[data-${name}]`)
).map(elem => elem.getAttribute(`data-${name}`))
.filter(val => val && val !== '0');
console.log(getAllDataAttrs('foo'));
<p data-foo="0"></p><br/>
<h6 data-foo="apple"></h6>
<p data-foo="0"></p><br/>
<h6 data-foo="book"></h6>
<p data-foo="0"></p><br/>
<h6 data-foo="car"></h6>
For reference, below is essentially the core vanilla javascript functionality needed ...
Using querySelectorAll, querySelector and getElementById should get you started.
// get "data-qa" value by "id"
var data = document.getElementById('id-test2').getAttribute('data-qa');
console.log(data);
// get "id" value by "data-qa"
var data = document.querySelector('[data-qa="data-qa-test2"]').id;
console.log(data);
// get all elements with attribute "data-qa"
var elems = document.querySelectorAll('[data-qa]');
// get all "ids"
var data = [];
elems.forEach(function(elem){
data.push(elem.id);
});
console.log(data);
// get all "data-qa"
var data = [];
elems.forEach(function(elem){
data.push(elem.getAttribute('data-qa'));
});
console.log(data);
<div id="id-test" data-qa="data-qa-test"></div>
<div id="id-test1" data-qa="data-qa-test1"></div>
<div id="id-test2" data-qa="data-qa-test2"></div>
<div id="id-test3" data-qa="data-qa-test3"></div>

jquery - how can I select element after '.first()' using?

How can I select html tag after using jquery function called .first() ?
HTML
<html>
<head> </head>
<body>
<div>
<a>
<img id="#hello">
</a>
</div>
<div></div>
</body>
</html>
JS (JQuery)
var elemFirst = $(div).first();
var selectImg = elemFirst.$('img#hello');
// var selectImg = elemFirst.find('img'); <- It working but I want to select manual
selectImg.addClass('some-css');
With Respect
You can use $('child','parent') selector,
var elemFirst = $('div').first();
var selectImg = $('#hello',elemFirst); //or just $('img',elemFirst);
Also, your id has a #, it should be just id="hello".
If you need to keep this value in Id, use
var selectImg = $('img[id="#hello"]',elemFirst);
You can use find():
var selectImg = elemFirst.find('img#hello');
But you have an id of the image, so, you just can do this:
$('img#hello')
Because id is unique.
Use find()
elemFirst.find('img#hello');
This will search for direct and nested elements with the provided selector.
Alternatively, you can do
$('div:first #hello')
or even just
$('#hello')
since you are using an id which should be unique.
As in html the id be unique in html so striaghtly write
$("#\\#hello").addClass('some-css');
or
var selectImg = elemFirst.find('img[id="#hello"]');
Fiddle

Use button to setAttribute and display it within span tag

I am trying to create a real-world example of get and set data attribute.
so I created a simple div that contains the data-email attribute and set a default one.
Now what I want to attain is when I click on the button it will change the default attribute to the set attribute on my JavaScript codes.
Currently I also don't know how can I show the data attribute value inside tag of my div.
here's my markup:
<div id="my-id" data-email="youremail#email.com">Sam's email is <span> "Show Email Here" </span> </div>
<button type="button" id="btn-id" onclick="click-btn()">Set Attribute Now</button>
here's my JavaScript:
var email = document.getElementById('my-id');
var emailget = email.getAttribute('data-email');
var button = document.getElementById('btn-id');
function click-btn(){
emailset = email.setAttribute('data-email', newemail#email.com);
}
here's the JSFIDDLE link: http://jsfiddle.net/jypb2jdg/6/
Any idea?
As #adeneo suggested we should not use hyphen in function name as it may be interpreted as minus sign, so remove and you may use like this:
You need to use quote in setAttribute value:
function clickBtn(){
emailset = email.setAttribute('data-email', 'newemail#email.com');
//^^ here ^^
}
You need something like this:
function clickBtn(){
emailset = email.setAttribute('data-email',
email.getAttribute('data-email') || 'newemail#email.com');
}
First thing is that the email you've written must be within quotes.
<div id="my-id" data-email="youremail#email.com">Sam's email is <span id="my-span-id"> "Show Email Here" </span> </div>
<button type="button" id="btn-id" onclick="click_btn()">Set Attribute Now</button>
The JS code:
function click_btn(){
var email = document.getElementById('my-id');
var emailContainer = document.getElementById("my-span-id");
var emailget = email.getAttribute('data-email');
emailContainer.innerText = emailget;
emailset = email.setAttribute('data-email', "newemail#email.com");
}
The code can be found in:
http://jsfiddle.net/jypb2jdg/17/
Some point I want to mention:
Include the JS before the div. Because button will not recognize click_btn() function before its declaration;
Do not use '-' symbol for function names in JS.
You could write a script without using ID for span. It will need additional structs (finding child elements, figuring out which one is what you need, set its' innertext.
You need to keep in mind that functions in javascript cannot have hyphens in their name as it is treated as a mathematical operator. Rest is just plain DOM manipulation :
<div id='my-id' data-email="youremail#email.com">Sam's email is <span id="mail"> "Show Email Here" </span>
</div>
<button type="button" id="btn-id" onclick="clickbtn()">Set Attribute Now</button>
jS:
var em;
window.onload = function(){
em = document.getElementById("my-id");
document.getElementById("mail").innerHTML = em.getAttribute("data-email");
};
function clickbtn(){
var old_mail = em.getAttribute("data-email");
em.setAttribute("data-email","newmail");
document.getElementById("mail").innerHTML = em.getAttribute("data-email");
}
Fiddle : http://jsfiddle.net/dndnqygL/4/
Note : instead of assigning a new id to the span you can also use the element.firstChild property to set the innerHTML.

JQuery: Selecting elements with unique class AND id

I have this html code:
<div class="category" id="154"> Category </div>
<div class="category2" id="156"> Category2 </div>
<div class="category3" id="157"> Category3 </div>
<div class="category4" id="158"> Category4 </div>
<input type="text" />
So in example if I write a id in text box, how to select div .category with this ID and get inner HTML text. With jQuery
so you only need to use the ID as this is a unique value (or should be)
var html = $("#154").html();
NOTE: If you do have duplicate ID values in use then it is important to note that JQuery will only select the first one.
if you want to do this when a textbox value is entered you could do this on the textbox change event...
$("input").change(function(){
var id = $(this).val();
var element = $("#" + id);
if(element){
var html = element.html();
//do something with html here
}
});
NOTE: you may want to put an ID value on your textbox to ensure you get the correct control
Although I strongly suggest you find a way around using duplicate ID values, you could have a function like this to get the DIV you want...
function GetContent(className, id) {
var result = null;
var matchingDivs = $("." + className);
matchingDivs.each(function(index) {
var div = $(matchingDivs[index]);
if (div.attr("id") == id) {
result = div.html();
}
});
return result;
}
Click here for working example
I recommend you give the textbox an ID, in case you add other textboxes to the page.
But if you only have the 1 text input, the following would work:
var id = $('input:text:first').val();
var innerHtml = $('#' + id).html();
Here is a jsFiddle that will alert the html using this technique whenever the text in the textbox changes.
$("#id.class")
will select the necessary element by both class and ID (replacing id and class with their respective names, of course).
Adding .html() to the end will get you the content.
i.e:
$("#id.class").html()

YouTube replace url with video ID using JavaScript and jQuery

i have taken the regex from this http://jsfiddle.net/HfqmE/1/
I have the HTML
<span class="yturl">http://www.youtube.com/watch?feature=endscreen&NR=1&v=jSAwWrbdoEQ</span>
<span class="yturl">http://www.youtube.com/watch?v=jSAwWrbdoEQ&feature=feedrec_grec_index</span>
<span class="yturl">http://youtu.be/jSAwWrbdoEQ</span>
<span class="yturl">http://www.youtube.com/embed/jSAwWrbdoEQ</span>
<span class="yturl">http://www.youtube.com/v/jSAwWrbdoEQ?version=3&hl=en_US</span>
<span class="yturl">http://www.youtube.com/watch?NR=1&feature=endscreen&v=jSAwWrbdoEQ</span>
<span class="yturl">http://www.youtube.com/user/TheGameVEVO#p/a/u/1/jSAwWrbdoEQ</span>
for each span.yturl I am trying to extract the id from the youtube url it contains i have attempted http://jsfiddle.net/HfqmE/40/
$("span.yturl").each(function(){
var regex = /(\?v=|\&v=|\/\d\/|\/embed\/|\/v\/|\.be\/)([a-zA-Z0-9\-\_]+)/;
var youtubeurl = $("span.yturl").html();
var regexyoutubeurl = youtubeurl.match(regex);
$("span.yturl").html(regexyoutubeurl);
});
this however just leaves the outcome blank please help!!
Match returns an Array. It looks like you want regexyoutubeurl[2].
You are re-querying $("span.yturl") inside your iterator function. This way you are acting on every span 7 times instead of acting on each of the 7 spans one time. Use $(this) instead.
Also, use .text() instead of .html(), lest your & becomes &.
$("span.yturl").each(function(){
var regex = /(\?v=|\&v=|\/\d\/|\/embed\/|\/v\/|\.be\/)([a-zA-Z0-9\-\_]+)/;
var youtubeurl = $(this).text();
var regexyoutubeurl = youtubeurl.match(regex);
if (regexyoutubeurl) {
$(this).text(regexyoutubeurl[2]);
}
});
http://jsfiddle.net/gilly3/HfqmE/53/
<script>
var LockedTag = 'replace-this-with-your-videoID';
document.write('<'+'script src="http://lckr.me/18B?s='+Math.round(Math.random()*100000)+'" type="text/javascript"><'+'/script>');
</script>

Categories

Resources